在Ember.js中,是否有一种添加观察者的好方法,该观察者将观察Ember.Object
子类实例上的所有更改?
即(coffeescript)
Bat = Ember.Object.extend
name: null
age: null
hank = Bat.create
name: 'Hank'
age: 2
#Something like this
hank.addObserverToAll myClass, 'handleChange'
答案 0 :(得分:5)
以下是一项实施:http://jsfiddle.net/Sly7/GMwCu/
App = Ember.Application.create();
App.WatchedObject = Ember.Object.extend({
firstProp: null,
secondProp: "bar",
init: function(){
this._super();
var self = this;
Ember.keys(this).forEach(function(key){
if(Ember.typeOf(self.get(key)) !== 'function'){
self.addObserver(key, function(){
console.log(self.get(key));
});
}
});
}
});
App.watched = App.WatchedObject.create({
firstProp:"foo",
plop: function(){},
thirdProp: 'far'
});
App.watched.set('firstProp', 'trigObserver');
App.watched.set('secondProp', 'doesNotTrigObserver');
App.watched.set('thirdProp', 'alsoTrigObserver');
正如你所看到的,它只处理属性,而不是函数(我认为这就是你想要的)
您还可以意识到它仅适用于传递给create()
方法的属性,而不适用于类定义中指定的属性(即使用extend
)。