2012-04-02 92 views

回答

11

Ember.js使用RunLoop的概念,允許綁定,觀察員等。

與實施例中的問題是,通過設置(結合的)屬性,並立即通過console.log獲取值沒有事件被觸發,其將觸發RunLoop和因此同步變化。有兩篇關於RunLoop的優秀博客文章:Part 1Part 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/

的Java腳本

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

隨着來看,我們也可以使用Ember.run.sync(),但只有一個呼叫,然後必要的。 http://jsfiddle.net/akLVy/10/ – 2012-04-02 16:35:10

+0

幹得好,克萊門斯 - 非常有幫助!我認爲我們需要在文檔中更好地解釋這一點。這對於初學者來說並不是一個很好的介紹,當其中一個例子沒有按「原樣」運行時。 – 2012-04-02 17:17:03

+0

謝謝!丹,我完全同意。這需要在文檔中更新! – pangratz 2012-04-02 17:18:37

3

你需要設置您的綁定給Ember的運行循環機率使你的日誌報表前同步之後調用Ember.run.sync();。這對於使用Ember進行測試也是一項方便的技術,但在Ember應用程序中通常不需要它們。