ember.js观察者的所有值 [英] ember.js observer for all values

查看:73
本文介绍了ember.js观察者的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ember.js中,是否有一种添加观察者的好方法,该观察者将会观察到 Ember.Object

的子类的实例上的所有更改

ie (coffeescript)

  Bat = Ember。 Object.extend 
name:null
age:null

hank = Bat.create
名称:'Hank'
年龄:2

#像这样
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()方法,而不是在类定义中指定的方法(即使用 extends )。


In Ember.js, is there a good way of adding an observer that will observe all changes on an instance of a subclass of Ember.Object?

ie (coffeescript)

Bat = Ember.Object.extend
    name: null
    age: null

hank = Bat.create
    name: 'Hank'
    age: 2

#Something like this
hank.addObserverToAll myClass, 'handleChange'

解决方案

Here is an implementation: 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');

As you can see, it handles only properties, not functions (I think it's what's you want).
You can also realize that it works only for properties passed to create() method, not those specified in the class definition (ie using extend).

这篇关于ember.js观察者的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆