ember.js – 无法使ember绑定按照记录的方式工作

前端之家收集整理的这篇文章主要介绍了ember.js – 无法使ember绑定按照记录的方式工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在emberjs.com上关注 documentation,但无法获得第一个绑定示例.

我创建了一个jsfiddle进行演示.我错过了什么?

解决方法

Ember.js使用RunLoop的概念来允许绑定,观察者等.

该示例的问题在于,通过设置(绑定)属性并立即通过console.log获取值,不会触发任何触发RunLoop并因此同步更改的事件.有两篇关于RunLoop的优秀博客文章Part 1Part 2.尽管他们以Sproutcore为目标,但Ember.js的概念大致相同.

有两种方法可以使您的示例正常工作.

通过Ember.run.sync()强制同步

正如文档所述,调用Ember.run.sync()…是一种立即强制应用程序中的所有绑定同步的有用方法.这样就留下了这样的代码,见http://jsfiddle.net/pangratz666/cwR3P/

  1. App = Ember.Application.create({});
  2. App.wife = Ember.Object.create({
  3. householdIncome: 80000
  4. });
  5.  
  6. App.husband = Ember.Object.create({
  7. householdIncomeBinding: 'App.wife.householdIncome'
  8. });
  9.  
  10. // force bindings to sync
  11. Ember.run.sync();
  12.  
  13. console.log(App.husband.get('householdIncome')); // 80000
  14.  
  15. // Someone gets raise.
  16. App.husband.set('householdIncome',90000);
  17.  
  18. // force bindings to sync
  19. Ember.run.sync();
  20.  
  21. console.log(App.wife.get('householdIncome')); // 90000​

或者第二个选择是……

在视图中显示

在视图中显示属性会为您处理所有RunLoop内容,请参阅http://jsfiddle.net/pangratz666/Ub97S/

JavaScript的:

  1. App = Ember.Application.create({});
  2. App.wife = Ember.Object.create({
  3. householdIncome: 80000
  4. });
  5.  
  6. App.husband = Ember.Object.create({
  7. householdIncomeBinding: 'App.wife.householdIncome'
  8. });
  9.  
  10. // invoke function in 3000ms
  11. Ember.run.later(function() {
  12. // someone gets a raise
  13. App.husband.set('householdIncome',90000);
  14. },3000);​

把手(视图):

  1. <script type="text/x-handlebars" >
  2. Wifes income: {{App.wife.householdIncome}}<br/>
  3. Husbands income: {{App.husband.householdIncome}}
  4. </script>

猜你在找的JavaScript相关文章