Skip to content Skip to sidebar Skip to footer

Ember.js Observer For All Values

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 n

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


Post a Comment for "Ember.js Observer For All Values"