Ember data: add a new element at the beginning of the array, not at the end

My application displays a message schedule. We retrieve them from the server in descending chronological order, from the latest to the oldest.

3 - Howdy 2 - Greetings 1 - Mahalo 

Our users also have the opportunity to add a new message, which by default will be inserted at the end of the queue so

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

When I send, I would like to see new messages at the top. I wrote a function before this changes the array of elements, but this will not work for elements 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 add content to an array, not to add. Is there any other option that could be better?

+4
source share
2 answers

For most sorting scenarios, it is recommented to use Ember.SortableMixin , which is baked in Ember.ArrayController .

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

In this example, the model has a DateTime field called when , which I use to filter:

 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 need to do is set the property name and sort direction:

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

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

Since in this example all dates coincide except for Forth (which due to sorting appear first), and also due to SortableMixin , these values ​​will be sorted through another property - I accept Id here.

Another approach I used in this fiddle is to use a computed property. I'm not quite sure about this approach, as it seems to consume more resources, and the code in App.SortingPropertyController deserves a laugh, but it seems to work to show the possibilities.

+5
source

Is it possible to use basic JavaScript to add a new element to a given location in an array? Not sure if these are basic ajax + js objects or full-sized ember-data models, but this works for a simple js array example

  var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join()); 

Code output above:

 Jani,Hege,Stale,Kai Jim,Borge Jani,Hege,Lene,Stale,Kai Jim, Borge 
-4
source

All Articles