Object.observe()
简介
This is an experimental technology, part of the Harmony (ECMAScript 7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.
上面是MDN 对于该方法的说明, Object.observe()用来实现异步监听对象的改变。
语法规则
Object.observe(obj,callback[,acceptList])
-
obj被监听的对象
-
每次对象改变的时候,执行的回调函数,该函数接受一个参数,类型为数组,数组中每个元素包含四个属性
1.name改变属性的名称
2.object改变之后的对象的值
3.type改变的类型,add, update或者delete
4.oldValue当type类型为update或者delete的时候,改变之前的属性值
- acceptList监听的事件类型, ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"]
自定义改变类型
除了上面指定的六种类型之外,["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"],我们可以自定义类型
// A point on a 2D plane
var point = {x: 0, y: 0, distance: 0};
function setPosition(pt, x, y) {
// Performing a custom change
Object.getNotifier(pt).performChange('reposition', function() {
var oldDistance = pt.distance;
pt.x = x;
pt.y = y;
pt.distance = Math.sqrt(x * x + y * y);
return {oldDistance: oldDistance};
});
}
Object.observe(point, function(changes) {
console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
}, ['reposition']);
setPosition(point, 3, 4);
// Distance change: 5