Shoan
Shoan

Reputation: 4078

Can't get ember bindings to work as documented

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?

Upvotes: 7

Views: 1555

Answers (2)

pangratz
pangratz

Reputation: 16153

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>​

Upvotes: 11

Dan Gebhardt
Dan Gebhardt

Reputation: 3281

You'll need to call Ember.run.sync(); after setting up your bindings to give Ember's run loop a chance to sync before your log statements. This is a handy technique for testing with Ember as well, but isn't typically needed in Ember apps themselves.

Upvotes: 3

Related Questions