Reputation: 18396
I will preface this with saying that I can not just use Ember ( big company with widely adopted templating solution that is not Handlebars and do not wish to re-implement the Ember.View ) as a whole and I just want to use a sub-set of Ember. In this case I'm using ember-runtime to try to take advantage of bindings. The problem is that these 2 objects are not staying in sync with each other. According to the docs they should be.
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')
console.log( App.myOtherObject.get('value') ); // bar
console.log( App.myObject.get('value') ); //foo
Upvotes: 2
Views: 79
Reputation: 19128
This is the expected behavior, because the bindings isn't propagated immediately. Instead it will be scheduled in the sync
queue. And this sync queue is flushed in the end of the current runloop.
Using bindings, you can change the value of an object several times, and the value will not be propagated unnecessarily. Just once.
For example in that sample:
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')
});
In your sample you can force the queue to be flushed using 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
Upvotes: 2