Can't get ember bindings to work as documented

谁说我不能喝 提交于 2019-12-21 11:01:07

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9978354/cant-get-ember-bindings-to-work-as-documented

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!