gpt4 book ai didi

ember.js - 无法让 ember 绑定(bind)按照记录工作

转载 作者:行者123 更新时间:2023-12-02 19:46:15 25 4
gpt4 key购买 nike

我正在关注documentation在 emberjs.com 上,但无法使第一个绑定(bind)示例正常工作。

我创建了一个jsfiddle展示。我错过了什么?

最佳答案

Ember.js 使用 RunLoop 的概念来允许绑定(bind)、观察者等。

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

有两种方法可以使您的示例发挥作用。

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

正如文档所述,调用 Ember.run.sync() ...是立即强制应用程序中的所有绑定(bind)同步的有用方法。这使得代码如下所示,请参阅 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​
<小时/>

或者第二个选择是...

在 View 中显示值

在 View 中显示属性可以为您处理所有 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);​

Handlebars ( View ):

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

关于ember.js - 无法让 ember 绑定(bind)按照记录工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9978354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com