Ember.js 入門指南——綁定(bingding)

   本系列文章全部從(http://ibeginner.sinaapp.com/)遷移過來,歡迎訪問原網站。


    ​正如其他的框架一樣Ember也包含了多種方式綁定實現,並且可以在任何一個對象上使用綁定。也就是說,綁定大多數情況都是使用在Ember框架本身,對於開發最好還是使用計算屬性。

1,雙向綁定

// 雙向綁定
Wife = Ember.Object.extend({
  householdIncome: 800
});
var wife = Wife.create();
 
Hasband = Ember.Object.extend({
  //  使用 alias方法實現綁定
  householdIncome: Ember.computed.alias('wife.householdIncome')
});
 
hasband = Hasband.create({
  wife: wife
});
 
console.log('householdIncome = ' + hasband.get('householdIncome'));  //  output > 800
// 可以雙向設置值
 
//  在wife方設置值
wife.set('householdIncome', 1000);
console.log('householdIncome = ' + hasband.get('householdIncome'));  // output > 1000
// 在hasband方設置值
hasband.set('householdIncome', 10);
console.log('wife householdIncome = ' + wife.get('householdIncome'));

blob.png

   需要注意的是綁定並不會立刻更新對應的值,Ember會等待直到程序代碼完成運行完成並且是在同步改變之前。所以你可以多次改變計算屬性的值,由於綁定是很短暫的所以也不需要擔心開銷問題。


2,單向綁定

       單向綁定只會在一個方向上傳播變化。相對雙向綁定來說,單向綁定做了性能優化,所以你可以安全的使用雙向綁定,對於雙向綁定如果你只是在一個方向上關聯其實就是一個單向綁定。

var user = Ember.Object.create({
  fullName: 'Kara Gates'
});
 
UserComponent = Ember.Component.extend({
  userName: Ember.computed.oneWay('user.fullName')
});
 
userComponent = UserComponent.create({
  user: user
});
 
console.log('fullName = ' + user.get('fullName'));
// 從user可以設置
user.set('fullName', "krang Gates");
console.log('component>> ' + userComponent.get('userName'));
// UserComponent 設置值,user並不能獲取,因爲是單向的綁定
userComponent.set('fullName', "ubuntuvim");
console.log('user >>> ' + user.get('fullName'));

blob.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章