更改字段后,Ember不会激活观察者

时间:2013-07-22 22:22:44

标签: attributes ember.js observers

当我更改字段时,设置观察者,观察者不能运行

App = Ember.Application.create();


App.Meeting = Em.Object.extend({
    id: null,
    name: null,
  proposes:{choice:5}
});

App.Meeting.reopen({
    proposedChanged: function() {
      var proposes = this.get('proposes');
      console.log(proposes);
      Ember.set(proposes, 'yesProcent', 'width:'+proposes.choice+'%');
      //this.set('proposes','width:'+10+'%');
      console.log(this);
    }.observes('proposes')
});

Ember.MyButton = Ember.Button.extend({
  click:function(){

      var meeting = this.get("meeting");

      meeting.proposes.choice = 10;

      Ember.set(meeting.proposes, 'choice', 10);
      meeting.set('proposes',meeting.proposes);
      console.log(meeting.proposes);
    }
});

App.meetingsController = Ember.ArrayController.create({
    content: [],
    loadList: function(){

        var me = this;

        var m = App.Meeting.create();
        m.setProperties({
          id : 1,
          name : 'Test',
          proposes: {choice:5}
        });

        me.pushObject(m);

    }
});

App.meetingsController.loadList();

从我的产品中有ailike代码,当fire observer属性(观察者中的变化)也没有改变时(对于那个例子我的意思是属性yesProcent)。 为什么呢?

来自示例jsbin

的来源

1 个答案:

答案 0 :(得分:1)

这里有一些事情在起作用。首先,当直接设置属性时,ember观察者不会触发:

meeting.proposes.choice = 10;
//Instead, use set like this:
meeting.set('proposes.choice',10);

更重要的是,这对观察者来说不是一个好的用例。你真正想要的是一个计算属性。见http://emberjs.com/guides/object-model/what-do-i-use-when/

App = Ember.Application.create();

App.Meeting = Em.Object.extend({
    id: null,
    name: null,
    proposes: {choice:5},
    yesProcent: function() {
       return 'width:' + this.get('proposes.choice') + '%';
    }.property('proposes.choice')
});

Ember.MyButton = Ember.Button.extend({
  click:function(){
    this.incrementProperty('meeting.proposes.choice');
  }
});

App.meetingsController = Ember.ArrayController.create({
    content: [],
    loadList: function(){
        var m = App.Meeting.create({
          id : 1,
          name : 'Test',
          proposes: {choice:25}
        });
        this.pushObject(m);
    }
});

App.meetingsController.loadList();

请参阅此处的工作示例:http://jsbin.com/avebok/5/edit