2.6 The Object Model -- Bindings

一个binding在两个属性之间创建一个链接,当一个改变时,另外一个被自动更新为一个新的值。

bindings可以在同一个对象中连接两个属性,或者用在两个不同的对象中。

不像大多数框架一样包含某种形式的绑定实现,在Ember.js中bindings可以被用于任何对象,而不仅仅是在viewsmodels之间。

1. Two-Way Binding

创建一个双向绑定的最简单的方法是使用一个计算的别名,它指定另一个对象的路径。

wife = Ember.Object.create({
    householdIncome: 80000
});

Husband = Ember.Object.extend({
    houseHoldIncome: Ember.computed.alias('wife.householdIncome')
});

husband = Husband.create({
    wife: wife
});

husband.get('householdIncome');//80000

//Someone gets raise.
wife.set('householdIncome', 90000);
husband.get('householdIncome');//90000
  • 注意绑定不会立刻更新。Ember等待直到同步改变之前所有的程序代码完成运行,所以当值是短暂的时候你可以改变一个绑定属性多次而无需担心同步绑定的开销。

2. One-Way Bindings

单向绑定只能在一个方向上传递变化。通常,单向绑定只是一个性能优化,你可以安全的使用双向绑定(当然,如果你只改变一个方向,双向绑定在事实上是单向绑定)。

有时单向绑定实现一些特定的行为是很有用的,例如一个默认的和另外一个属性一样的但是可以被重写。(如送货地址,开始与一个账单地址相同,但是稍后可以被改变)

user = Ember.Object.create({
    fullName: "Kara Gates"
});

UserView = Ember.View.extend({
    userName: Ember.computed.oneWay('user.fullName')
});

userView = UserView.create({
    user: user
});

//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.setr('userName', "Truckasaurus Gates");
user.get('fullName');//"Krang Gates"
原文地址:https://www.cnblogs.com/sunshineground/p/5147978.html