gpt4 book ai didi

javascript - 所有值的 ember.js 观察者

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:37:09 25 4
gpt4 key购买 nike

在 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'

最佳答案

这是一个实现: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)。

关于javascript - 所有值的 ember.js 观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com