I am following the documentation on emberjs.com, but can't get the first bindings example to work.
I created a jsfiddle to demonstrate. What am I missing?
Ember.js uses the concept of a RunLoop to allow bindings, observers and so on.
The problem with the example is that by setting a (bound) property and immediately getting the value via console.log
no event is fired which would trigger the RunLoop and therefore synchronize the changes. There are 2 excellent blog posts about the RunLoop: Part 1 and Part 2. Although they target Sproutcore, the concept is about the same for Ember.js.
There are two ways to make your example work.
Force synchronisation via Ember.run.sync()
As the docs state, invoking Ember.run.sync()
... is a useful way to immediately force all bindings in the application to sync. This leaves the code like this, see http://jsfiddle.net/pangratz666/cwR3P/
App = Ember.Application.create({});
App.wife = Ember.Object.create({
householdIncome: 80000
});
App.husband = Ember.Object.create({
householdIncomeBinding: 'App.wife.householdIncome'
});
// force bindings to sync
Ember.run.sync();
console.log(App.husband.get('householdIncome')); // 80000
// Someone gets raise.
App.husband.set('householdIncome', 90000);
// force bindings to sync
Ember.run.sync();
console.log(App.wife.get('householdIncome')); // 90000
Or the second option is to ...
Show the values in a view
Showing the properties in a view handles all the RunLoop stuff for you, see http://jsfiddle.net/pangratz666/Ub97S/
JavaScript:
App = Ember.Application.create({});
App.wife = Ember.Object.create({
householdIncome: 80000
});
App.husband = Ember.Object.create({
householdIncomeBinding: 'App.wife.householdIncome'
});
// invoke function in 3000ms
Ember.run.later(function() {
// someone gets a raise
App.husband.set('householdIncome', 90000);
}, 3000);
Handlebars (the view):
<script type="text/x-handlebars" >
Wifes income: {{App.wife.householdIncome}}<br/>
Husbands income: {{App.husband.householdIncome}}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With