Observer are not called on create()

前提是你 提交于 2020-01-01 09:54:09

问题


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');
      }
    }
});

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/11412550/observer-are-not-called-on-create

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