Ember学习(7):Bindings

来源:互联网 发布:php写文件换行 编辑:程序博客网 时间:2024/05/18 00:05

英文原址:http://emberjs.com/guides/object-model/bindings/

binding可以在两个属性之间创建一个连接关系,当其中一个变化时,另一个会自动获得变化后的新值。binding可以连接同一个对象的属性,也可以连接不同对象的属性。不像很多其他的框架,binding需要某种特殊的实现,Ember中得binding很容易使用,可以用在任意类型的object之间,不仅仅局限于view可以model之间。


双向Binding

最简单的创建双向binding的方法就是使用computed alias,它可以指定另一个对象的路径:

wife = Ember.Object.create({  householdIncome: 80000});husband = Ember.Object.create({  wife: wife,  householdIncome: Ember.computed.alias('wife.householdIncome')});husband.get('householdIncome'); // 80000// Someone gets raise.husband.set('householdIncome', 90000);wife.get('householdIncome'); // 90000
注意binding不会立刻就更新。Ember会等你应用的代码都运行完了,才开始同步变化,因此你可以对连接的属性做很多次的改变,而不用担心会有任何的额外开销发生在中间的临时值上。

单向Binding

单向binding只会在一个方向上同步改变。通常,单向binding只是一种作为对双向binding的一种优化性能的选择,因此你一般都可以安全使用双向binding(而且,只要你永远只在一个属性上做出改变,那么双向binding也就退化成了单向binding)。有时,单向binding可以用来实现一些特殊的行为,比如说给属性设置一个来自其他属性的默认值,而这个默认值可以被自由的改变,而不用担心会影响原始的默认值(比如一个邮寄地址可以默认设置为和账单地址相同,但是之后可以独立的修改)。

user = Ember.Object.create({  fullName: "Kara Gates"});userView = Ember.View.create({  user: user,  userName: Ember.computed.oneWay('user.fullName')});// Changing the name of the user object changes// the value on the view.user.set('fullName', "Krang Gates");// userView.userName will become "Krang Gates"// ...but changes to the view don't make it back to// the object.userView.set('userName', "Truckasaurus Gates");user.get('fullName'); // "Krang Gates"

0 0
原创粉丝点击