这是预期的行为,因为绑定不会立即传播。相反,它将被安排在sync
队列中。并且这个同步队列在当前运行循环结束时被刷新。
使用绑定,您可以多次更改对象的值,并且不会不必要地传播该值。就一次。
例如在该示例中:
App.IndexRoute = Ember.Route.extend({
afterModel: function() {
this.controllerFor('index').someAction();
}
});
App.IndexController = Ember.Controller.extend({
minBinding: 'minNumber',
minNumber: Number.MAX_VALUE,
someAction: function() {
var self = this;
[3,2,3,5,3,6,7,9,4,1].forEach(function(number) {
if (self.get('minNumber') > number) {
self.set('minNumber', number);
}
});
},
// this observer is called 3 times
minNumberChanged: function() {
console.log('minNumberChanged', this.get('minNumber'))
}.observes('minNumber'),
// this observer is called once
minChanged: function() {
console.log('minChanged', this.get('min'))
}.observes('min')
});
在您的示例中,您可以使用强制刷新队列Ember.run.sync()
。
var App = Ember.Application.create();
App.myObject = Ember.Object.create({
value: null
});
App.myOtherObject = Ember.Object.create({
value: 'foo'
});
Ember.bind( App.myObject, 'value', 'App.myOtherObject.value' );
console.log( App.myObject.get('value') ); // foo
console.log( App.myOtherObject.get('value') ); // foo
App.myOtherObject.set('value', 'bar')
Ember.run.sync() // this will force the bindings to be propagated
console.log( App.myOtherObject.get('value') ); // bar
console.log( App.myObject.get('value') ); //bar