lcoq
lcoq

Reputation: 10726

Observer are not called on create()

I have a Ember.Mixin which observes one of its properties (here bar.baz).

I've extended this Mixin and set bar.baz in the .create() parameter, but my observer is not called.

Here is my code :

App.FooMixin = Ember.Mixin.create({
    barBazDidChange: function() {
        console.log('barBazDidChange'); // never called
    }.observes("bar.baz")
});

App.Foo = Ember.Object.extend(App.FooMixin);

App.fooObject = App.Foo.create({
    bar: Ember.Object.create({
        baz: "ember"
    })
});​

And the associated jsfiddle : http://jsfiddle.net/aMQmn/

I could of course call the observer in the init() method like below, but I wonder if there is a better solution (or if this solution is the proper way to do that) :

App.FooMixin = Ember.Mixin.create({
    init: function() {
      this._super();
      if (this.getPath('bar.baz')) { 
        this.notifyPropertyChange('bar.baz');
      }
    }
});

Upvotes: 6

Views: 1281

Answers (2)

Peter Wagenet
Peter Wagenet

Reputation: 5056

The correct solution is to override the init method (make sure to call this._super()) and call the function there. As others have noted, the observer is not firing because the value is not actually changing. There has been some discussion around making create behave more like setProperties which would make this a non-issue.

Upvotes: 3

sly7_7
sly7_7

Reputation: 12011

So no answer during 7days... what I would do instead of passing the property at creation time is chaining the creation and setting the property, like this:

App.fooObject = App.Foo.create().set('bar', Ember.Object.create({baz: "ember"}));​

If it's not satisfying enough, perhaps you could post an issue in the ember project on github: https://github.com/emberjs/ember.js/issues

Upvotes: 3

Related Questions