如何在Ember.js中推送/弹出数组?

Luk*_*nis 35 javascript sproutcore ember.js

我可以在Ember对象中包含一个数组,并使用Handlebars显示内容.但是,我只能使用set()替换数组内容.如何使用push/pop/etc修改数组内容.并且仍然有UI绑定更新?

// 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}}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ert 69

对于使用集合,Ember.js提供了一个Array包装类,Ember.Array/Ember.MutableArray

因此,不使用普通数组,而是使用以下代码:

// 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}}
Run Code Online (Sandbox Code Playgroud)

  • pushObject和它的朋友(popObject,removeAt等)的有用参考:http://ember-docs.herokuapp.com/symbols/Ember.MutableArray.html (7认同)