我可以在 Ember 对象中包含一个数组,并使用 Handlebars 显示内容。但是,我只能使用 set() 替换数组内容。如何使用 push/pop/etc 修改数组内容。并且仍然有 UI 绑定(bind)更新?
// 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}}
最佳答案
为了处理集合,Ember.js 提供了一个数组包装类,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}}
关于javascript - 如何在 Ember.js 中推送/弹出数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9061107/