你是否可以监听对象的变化并在发生变化时做出反应,而不是基于用户操作触发事件?
你是否可以监听对象的变化并在发生变化时做出反应,而不是基于用户操作触发事件?
person.on('name.change', function(val){
// 'a new name was committed: Yolanda'
console.log('a new name was committed: ', val)
});
person.name = 'Yolanda';
https://github.com/jmoyers/mettle/blob/master/src/model.coffee
如果你需要深入了解源代码,可能需要花费一些时间。以下是解释:
我的项目的关键是两个概念。一个是通过使用defineGetter和defineSetter为一组属性跟踪并创建getter和setter。第二个是“子类化”EventEmitter,在setter中基于这些属性更改广播事件。
Track展示了我如何为一组键设置getter/setter。
Model.prototype.track = function(keys) {
_.each(keys, __bind(function(key) {
this.tracked.push(key);
this.__defineGetter__(key, __bind(function() {
return this.get(key);
}, this));
return this.__defineSetter__(key, __bind(function(val) {
return this.set(key, val);
}, this));
}, this));
return this;
};
Model.prototype.set = function(key, val) {
this.attribs[key] = val;
this.emit('change', this.attribs);
type = key + '.change';
this.emit(type, val);
};
这是一个简化的示例,因为我引入了“属性中间件”,但这展示了如何根据属性更改发出更改事件。