[英]how to observe changes in an array within controller/component
How can we observe changes to an array in Ember? 我们如何观察Ember中阵列的变化? I have ember component that uses raw object data from a model, but to demonstrate the issue I am using array property within component itself like: 我有使用模型中原始对象数据的余烬组件,但是为了演示这个问题,我在组件本身内部使用了数组属性,例如:
init:function(){
this._super();
var arr = Ember.A([
Ember.Object.create({"shelfNo": 1, "noOfItems": 2}),
Ember.Object.create({"shelfNo": 2, "noOfItems": 3}),
Ember.Object.create({"shelfNo": 3, "noOfItems": 2})]
);
this.set("someArray",arr);
//DOES NOT WORK
this.get('someArray').addArrayObserver(function () {
Ember.ObjectController.create({
arrayWillChange: function (observedObj, start, removeCount, addCount) {
console.log("in arrayWillChange");
},
arrayDidChange: function (array, start, removeCount, addCount) {
console.log("in arrayDidChange");
}
});
});
}
I also tried : 我也尝试过:
testObserver: function(){
//DOES NOT WORK
console.log("here");
}.observes('someArray@each')
But both didn't work for me! 但是两者都不适合我!
Here is a jsbin : http://jsbin.com/EkumOjA/1/ 这是一个jsbin: http ://jsbin.com/EkumOjA/1/
Thanks, Dee 谢谢迪
If you are observing a property from some object in the array use someArray.@each.someProperty
. 如果要从数组中的某个对象观察属性,请使用someArray.@each.someProperty
。 To observe when the array content change (someArray.pushObject, removeObject etc) use someArray.[]
or someArray.length
. 要观察数组内容何时更改(someArray.pushObject,removeObject等),请使用someArray.[]
或someArray.length
。
Also, instead of override init
use someFunc: function() {}.on('init')
this is the safe way to get observers working, on object initialization. 另外,不要使用someFunc: function() {}.on('init')
覆盖init
这是使观察者能够进行对象初始化的安全方法。
This is your updated code: 这是您更新的代码:
App.ShowQuestionComponent = Ember.Component.extend({
someArray : null,
initializeSomeArray:function(){
var arr = Ember.A([
Ember.Object.create({"shelfNo": 1, "noOfItems": 2}),
Ember.Object.create({"shelfNo": 2, "noOfItems": 3}),
Ember.Object.create({"shelfNo": 3, "noOfItems": 2})]
);
this.set("someArray",arr);
}.on('init'),
testObserver: function(){
console.log("here");
}.observes('someArray.[]')
});
And your updated jsbin http://jsbin.com/EkumOjA/2/edit 和您更新的jsbin http://jsbin.com/EkumOjA/2/edit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.