我试图了解Object.getNotifier(object).performChange
。从概念上讲,我知道它是为定义“宏观”或更高级更改而设计的。从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
});
}
我不明白的是,这与直接执行传递给
notifier.performChange
而不是作为回调的匿名函数有何不同?换句话说,它与以下内容有何不同:increment: function(amount) {
var notifier = Object.getNotifier(this);
this.a += amount;
this.b += amount;
notifier.notify({
object: this,
type: Thingy.INCREMENT,
incremented: amount
});
}
我已经看到,在最新的规范中,
notifier.performChange
可能返回一个对象,然后将该对象作为通知发出,如: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};
});
这就消除了在原始代码中使用以下
notifier.notify
的需要,但是,这仍然不是糖,还是在功能上与仅进行更改并自己发出通知之间存在功能差异? 最佳答案
经过一个小时的大量测试,我终于弄明白了。我有相同的问题(performChange
代表什么?),也有相同的想法将其删除并致电
this.a += amount;
this.b += amount;
但是:
notifier.performChange
的要点是,观察者不会观察到每个更改。我正在像这样测试它:
var obj = {
x: 5,
y: 10
};
function noti() {
console.log('noti start');
var notifier = Object.getNotifier(obj);
notifier.performChange('ok', function() {
obj.x++;
obj.y++;
});
notifier.notify({
type: 'ok',
oldValue: 5
});
console.log('noti end');
};
function noti2() {
console.log('noti2 start');
var notifier = Object.getNotifier(obj);
obj.x++;
obj.y++;
notifier.notify({
type: 'ok',
oldValue: 5
});
console.log('noti2 end');
};
function observer(changes) {
for (var change of changes) {
console.log('observer: change =', change, ' newValue=', change.object[change.name]);
}
};
Object.observe(obj, observer, ['ok', 'update']);
console.log('calling noti2()');
noti2(); //will log the changes of update twice becuase of the x and y property of obj
// add delay manually because observer calls are asynchronous and
// we want to clearly separate the notification function calls in our logs
setTimeout(function() {
console.log('calling noti()');
noti(); //will only log the ok type. that's what they mean by big change
//so everything you do inside the performChange won't be observed
}, 100);
它应该返回以下控制台输出:
calling noti2()
noti2 start
noti2 end
observer: change = Object {type: "update", object: Object, name: "x", oldValue: 5} newValue= 6
observer: change = Object {type: "update", object: Object, name: "y", oldValue: 10} newValue= 11
observer: change = Object {object: Object, type: "ok", oldValue: 5} newValue= undefined
calling noti()
noti start
noti end
observer: change = Object {object: Object, type: "ok", oldValue: 5} newValue= undefined