Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push/pop arrays in Ember.js?

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}}
like image 346
Luke Dennis Avatar asked Jan 30 '12 08:01

Luke Dennis


1 Answers

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}}
like image 141
Michael Siebert Avatar answered Nov 15 '22 06:11

Michael Siebert