2

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

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();

从我的项目中,有类似的代码,并且当火观察者属性(观察者发生变化)也没有改变(对于那个例子,我的意思是属性 yesProcent)。为什么?

源到示例jsbin

4

1 回答 1

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

于 2013-07-23T01:54:13.677 回答