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'));

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

   需要注意的是绑定并不会立刻更新对应的值,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'));

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

版权声明:本文为博主原创文章,未经博主允许不得转载。