Reputation: 2465
How can we observe changes to an array in 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/
Thanks, Dee
Upvotes: 1
Views: 2991
Reputation: 19128
If you are observing a property from some object in the array use [email protected]
. To observe when the array content change (someArray.pushObject, removeObject etc) use someArray.[]
or someArray.length
.
Also, instead of override init
use someFunc: function() {}.on('init')
this is the safe way to get observers working, on object initialization.
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
Upvotes: 6