Reputation: 4222
I'm observing a controller property (an object) in my view with @each
. Every time, @each
changes, I want to know, which item has changed.
Is there a way to find it out?
Docket.OrganizationView = Ember.View.extend({
chartObserver: function() {
console.log(THE_ITEM_OF_CHARTDATA_THAT_HAS_CHANGED)
}.observes('controller.chartData.@each')
});
Upvotes: 2
Views: 261
Reputation: 10077
Use an observesBefore
call to store the array before it changes, so that you can compare it with the array after the change:
Docket.OrganizationView = Ember.View.extend({
chartDataWillChange: function() {
this._oldChartData = this.get('controller.chartData').slice(0);
}.observesBefore('controller.chartData.@each')
chartDataDidChange: function() {
var oldChartData = this._oldChartData;
var newChartData = this.get('controller.chartData');
// Compare the contents of the two arrays
// to find out what has changed
var addedItems = newChartData.filter(function(item) {
return !oldChartData.contains(item);
});
var removedItems = oldChartData.filter(function(item) {
return !newChartData.contains(item);
});
}.observes('controller.chartData.@each')
});
Upvotes: 1
Reputation: 2861
You could define a ArrayComputed property in your controller as this example.
ArrayComputed: Creates a computed property which operates on dependent arrays and is updated with "one at a time" semantics.
Ember.ArrayController.extend({
changedContent: Ember.arrayComputed("[email protected]", {
addedItem: function(array, item, changeMeta, instanceMeta) {
array.clear();
array.pushObject(item);
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
array.clear();
array.pushObject(item);
return array;
}
}),
});
Upvotes: 1