Ruby's Louvre

每天学习一点点算法

导航

属性监听器

在Proxy没有标准化之前,FF的Object.prototype.watch可是一个好东西。通过ecma262v5的特性描述符,我们可以实现此功能,这用于node.js最好不过了。

if ( ! Object.prototype.watch) {
	Object.defineProperty(Object.prototype, 'watch', {
		value: function (prop, handler) {
			var val = this[prop];
			var getter = function () {
				return val;
			};
			var setter = function (newVal) {
				var val = handler.call(this, prop, val, newVal);
			};
			if (delete (this[prop])) {
				Object.defineProperty(this, prop, {
					get: getter,
					set: setter,
					configurable: true
				});
			}
		}
	});
}
/**
 * Object.unwatch() - Removes a watchpoint set with the watch method.
 * @param prop
 */
if ( ! Object.prototype.unwatch) {
	Object.defineProperty(Object.prototype, 'unwatch', {
		value: function (prop) {
			var val = this[prop];
			delete (this[prop]);
			this[prop] = val;
		}
	});
}

posted on 2011-12-13 18:58  司徒正美  阅读(1845)  评论(2编辑  收藏  举报