4

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'
3
  • This might help: stackoverflow.com/questions/9193712/…
    – Rajat
    Jul 24, 2012 at 6:18
  • Thanks! But it looks like that poor guy never got a good answer... And he asked 5 months ago. :(
    – wmarbut
    Jul 24, 2012 at 13:15
  • @Rajat also the article that is linked in that post no longer seems to be valid or the current build of ember
    – wmarbut
    Jul 26, 2012 at 18:23

1 Answer 1

5

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

3
  • Thanks man, was hoping Ember handled it natively, but this is an elegant solution!
    – wmarbut
    Jul 27, 2012 at 21:27
  • N.B. It only observes properties passed at the create method. Not those specified in the class definition (using extend).
    – lcoq
    Aug 20, 2012 at 17:53
  • Yep, that's what I said in my comment below the code, but it seems not clear, I update. Thanks @louiscoquio
    – sly7_7
    Aug 20, 2012 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.