Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

ember.js - Ember data: Insert new item at beginning of array instead of at the end

In my application I'm displaying a timeline of messages. We retrieve them from the server in descending chronological order, newest to oldest.

3 - Howdy
2 - Greetings
1 - Mahalo

Our users also have the ability to add a new message which by default gets inserted at the end of the queue like so

3 - Howdy
2 - Greetings
1 - Mahalo
4 - I'm the new message, last as usual

When I submit, I'd like new messages to show up at the top. I've written a function before that reverses the array of items, but that wouldn't work for items already in the array.

4 - I'm the new message, first finally
3 - Howdy
2 - Greetings
1 - Mahalo

What would be the best approach in this case? The ideal would be for Ember Data to prepend to the content array rather than append. Is there another option which might be better?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For most scenarios involving sorting it's recommented to use Ember.SortableMixin, which is baked into Ember.ArrayController.

Please refer to this conceptual example in JSFiddle: http://jsfiddle.net/schawaska/tbbAe/

In this sample the model has a DateTime field named when, which I'm using for filtering:

App.Greeting = DS.Model.extend({
    text: DS.attr('string'),
    when: DS.attr('date')                  
});

App.Greeting.FIXTURES = [
    {id: 1, text: 'First', when: '3/4/2013 2:44:52 PM'},
    {id: 2, text: 'Second', when: '3/4/2013 2:44:52 PM'},
    {id: 3, text: 'Third', when: '3/4/2013 2:44:52 PM'},
    {id: 4, text: 'Fourth', when: '3/4/2013 3:44:52 PM'}
];

In the controller the only thing I have to do is to set the name of the property and the sorting direction:

App.SortingMixinController = Em.ArrayController.extend({
    sortProperties: ['when'],
    sortAscending: false
});

Then in my Handlebars template, I can use the {{each}} helper as I would do normally.

Because in this sample, all the dates are the same except for the Forth (which because of sorting appears first), and also because of SortableMixin, these values will be sorted through another property - I'm assuming the Id here.

The other approach I've taken in that fiddle is using a computed property. I'm not really sure about that approach as it seems to consume more resources and the code in App.SortingPropertyController is worthy of laugh, but sort of works to show possibilities.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...