Javascript 如何在 Ember.js 中推送/弹出数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9061107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to push/pop arrays in Ember.js?
提问by Luke Dennis
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?
我可以在 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}}
回答by Michael Siebert
For working with collections, Ember.js provides an Array wrapper class, Ember.Array / Ember.MutableArray
为了处理集合,Ember.js 提供了一个数组包装类 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}}
回答by Mad Scientist
Use an instance of Ember.ArrayController,simply declaring an array with [] will also create array of Ember.ArrayController class.
使用 Ember.ArrayController 的实例,简单地用 [] 声明一个数组也会创建 Ember.ArrayController 类的数组。
If you want to add an Object at the end of Ember ArrayController you can use the addObject() method;
如果你想在 Ember ArrayController 的末尾添加一个 Object 你可以使用 addObject() 方法;
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')