36

I can include an array in an Ember object, and display the contents using Handlebars. However, I can only replace the array contents using set(). How can I modify the array contents using push/pop/etc. and still have the UI bindings update?

// JS
App.obj = Ember.Object.create({
    "things": ["1", "2"],
});
App.obj.set("things", ["1", "2", "3"]); // Works
App.obj.things.push("3"); // Doesn't Work

// HTML + Handlebars
{{#with App.obj}}
    <ul>
    {{#each things}}
        <li>{{this}}</li>
    {{/each}}
    </ul>
{{/with}}
Luke Dennis
  • 14,212
  • 17
  • 56
  • 69

2 Answers2

71

For working with collections, Ember.js provides an Array wrapper class, Ember.Array / Ember.MutableArray

So, instead of using a plain array, use these:

// JS
App.obj = Ember.Object.create({
    "things": Ember.A(["1", "2"])
});
App.obj.things.pushObject("3"); // pushObject notifies observers

// HTML + Handlebars
{{#with App.obj}}
    <ul>
    {{#each things}}
        <li>{{this}}</li>
    {{/each}}
    </ul>
{{/with}}
Michael Siebert
  • 2,378
  • 1
  • 20
  • 17
  • 7
    Helpful reference for pushObject and it friends (popObject, removeAt, etc): http://ember-docs.herokuapp.com/symbols/Ember.MutableArray.html – Luke Melia Mar 01 '12 at 17:08
  • 1
    Here is also useful answer why you need to use those methods: http://stackoverflow.com/questions/14582759/ember-containerview-not-updating-in-response-to-childviews-push – zigomir May 27 '13 at 13:30
0

Use an instance of Ember.ArrayController,simply declaring an array with [] will also create array of Ember.ArrayController class.

If you want to add an Object at the end of Ember ArrayController you can use the addObject() method;

eg.

mutableArray:[],

setModel:function(){

var data1={'id':1,'name':'over'};
var data2={'id':3,'name':'out'};

this.get('mutableArray').addObject(data1);
this.get('mutableArray').addObject(data2);

/* To Add Object to middle of array at given index simply use the native array splice method */

var data1={'id':2,'name':'and'}
this.get('mutableArray').splice(1,0,data1);

return this.get('mutableArray')

}.property('mutableArray')
Mad Scientist
  • 340
  • 4
  • 14
  • 3
    Best to avoid using Ember.ArrayController now since it has been deprecated. Use the Ember.Array or Ember.ArrayProxy classes instead. – SeanK Aug 10 '15 at 16:41