When i change field, from which set observer, observer not run

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

From my prodject have ailike code and when fire observer attribute(which change in observer) not changed too(for that example i mean attribute yesProcent). Why?

Source to example jsbin

有帮助吗?

解决方案

There are a few things at play here. First, ember observers will not fire when properties are set directly like:

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

More importantly, this is just not a good use case for observers. What you really want is a computed property.See 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();

See working example here: http://jsbin.com/avebok/5/edit

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top