Reputation: 28547
In an Ember.ArrayController
, I have a function that .observes()
a property on the entire array of the model for a property change.
var FoosController = Ember.ArrayController.extend(Ember.Evented, {
observesEachFooBar: function() {
var foos = this.get('model');
foos.forEach(function(foo) {
//test if this foo has changed, then do something
});
}.observes('[email protected]'),
});
Here I am manually testing every single Foo
in its model.
How can I avoid doing this, and just be given the individual one (or few)
that have changed?
Upvotes: 1
Views: 437
Reputation: 31789
Here is an example using the addArrayObserver
method, along with arrayContentWillChange
and arrayContentDidChange
.
App.IndexController = Em.ArrayController.extend({
initializer: function() {
this.addArrayObserver({
arrayWillChange: Em.K,
arrayDidChange: function(observedObj, start, removeCount, addCount) {
if(!removeCount && !addCount) {
alert('Array item at ' +start+ ' updated');
}
}
});
}.on('init'),
actions: {
updateData: function() {
this.get('content').arrayContentWillChange(3, 0, 0);
this.set('content.3.foo', 'foo3-updated');
this.get('content').arrayContentDidChange(3, 0, 0);
}
}
});
Upvotes: 0
Reputation: 47367
Ember does this with the SortableMixin. You can follow the same pattern.
forEach(sortProperties, function(sortProperty) {
addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
}, this);
}, this);
}
return this._super(array, idx, removedCount, addedCount);
},
insertItemSorted: function(item) {
var arrangedContent = get(this, 'arrangedContent');
var length = get(arrangedContent, 'length');
var idx = this._binarySearch(item, 0, length);
arrangedContent.insertAt(idx, item);
},
contentItemSortPropertyDidChange: function(item) {
var arrangedContent = get(this, 'arrangedContent'),
oldIndex = arrangedContent.indexOf(item),
leftItem = arrangedContent.objectAt(oldIndex - 1),
rightItem = arrangedContent.objectAt(oldIndex + 1),
leftResult = leftItem && this.orderBy(item, leftItem),
rightResult = rightItem && this.orderBy(item, rightItem);
if (leftResult < 0 || rightResult > 0) {
arrangedContent.removeObject(item);
this.insertItemSorted(item);
}
},
Upvotes: 2