我在emberjs.com上关注
documentation,但无法获得第一个绑定示例.
我创建了一个jsfiddle进行演示.我错过了什么?
解决方法
Ember.js使用RunLoop的概念来允许绑定,观察者等.
该示例的问题在于,通过设置(绑定)属性并立即通过console.log获取值,不会触发任何触发RunLoop并因此同步更改的事件.有两篇关于RunLoop的优秀博客文章:Part 1和Part 2.尽管他们以Sproutcore为目标,但Ember.js的概念大致相同.
有两种方法可以使您的示例正常工作.
通过Ember.run.sync()强制同步
正如文档所述,调用Ember.run.sync()…是一种立即强制应用程序中的所有绑定同步的有用方法.这样就留下了这样的代码,见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
或者第二个选择是……
在视图中显示值
在视图中显示属性会为您处理所有RunLoop内容,请参阅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);
把手(视图):
- <script type="text/x-handlebars" >
- Wifes income: {{App.wife.householdIncome}}<br/>
- Husbands income: {{App.husband.householdIncome}}
- </script>