ember.js observer for all values

痞子三分冷 提交于 2019-12-19 22:01:46

问题


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'

回答1:


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).



来源:https://stackoverflow.com/questions/11623645/ember-js-observer-for-all-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!