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
    name: null
    age: null

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

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

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.