Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get ember bindings to work as documented

Tags:

ember.js

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?

like image 596
Shoan Avatar asked Apr 02 '12 14:04

Shoan


1 Answers

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>​
like image 68
pangratz Avatar answered Oct 13 '22 00:10

pangratz