Search code examples
ember.jsember-model

ember js how to push object to the top of the stack in the ArrayController


I have this controller where to fetch data from the server I have to fire fetchPosts method and to add new post fire add

App.PostsController = Ember.ArrayController.extend({
  actions: {
    fetchPosts: function (id) {
      var data = App.Post.find({category: id});
      this.set('model', data);
    },
    add: function () {
      var post = this.get('newPost');
      post.save().then(function () { 
        this.pushObject(post);
      });
   }
});

The problem is that the record are adding to the bottom of the list. I want it to work like native js unshift but now it works like push . Looking for something like unshiftObject to make added object the first object in the array.


Solution

  • unshiftObject works in Ember http://emberjs.com/api/classes/Ember.MutableArray.html#method_unshiftObject.

    Your code has an out of scope issue here:

      var post = this.get('newPost');
      post.save().then(function () { 
        this.pushObject(post); // <----- this this wouldn't be the array controller
      });