Ember.js 入门指南——绑定(bingding)

   本系列文章所有从(http://ibeginner.sinaapp.com/)迁移过来,欢迎访问原网站。ubuntu


    正如其余的框架同样Ember也包含了多种方式绑定实现,而且能够在任何一个对象上使用绑定。也就是说,绑定大多数状况都是使用在Ember框架自己,对于开发最好仍是使用计算属性。vim

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

相关文章
相关标签/搜索