I am trying to understand Object.getNotifier(object).performChange
. Conceptually I understand that it is designed for defining "macro" or higher level changes. From the example everyone seems to refer to:
increment: function(amount) {
var notifier = Object.getNotifier(this);
notifier.performChange(Thingy.INCREMENT, function() {
this.a += amount;
this.b += amount;
}, this);
notifier.notify({
object: this,
type: Thingy.INCREMENT,
incremented: amount
});
}
What I do not understand is, how is this different from simply executing the anonymous function passed to notifier.performChange
directly, instead of as a callback? In other words, how does it differ from the below:
increment: function(amount) {
var notifier = Object.getNotifier(this);
this.a += amount;
this.b += amount;
notifier.notify({
object: this,
type: Thingy.INCREMENT,
incremented: amount
});
}
I have seen that in the latest spec, notifier.performChange
may return an object, which is then issued as a notification, as in:
notifier.performChange(Thing.INCREMENT, function() {
this.a += amount;
this.b += amount;
// a notification is issues with this return value,
// including the type passed to notifier.performChange,
// and the object underlying notifier.
return {incremented: amount};
});
That eliminates the need for the following notifier.notify
in the original code, but still, is this something other than sugar, or is there a functional difference between this and just making the changes and issuing the notification yourself?
After an hour of doing a lot of testing I finally figured it out. I had the same question (what is
performChange
for?), and also the same idea to just take that off and callHowever: the point of
notifier.performChange
is so that the observer does not observe each change.I was testing it like this:
It should return the following console output: