2.3 The Object Model -- Computed Properties

一、What are computed properties?

1. 简而言之,计算属性让你声明函数为属性。你通过定义一个计算属性作为一个函数来创建一个,当你请求这个属性时,Ember会自动调用这个function。

之后你可以用同样的方法使用它,任何正常静态属性。

2. 对于获取一个或多个正常的属性和转换或者操纵它们的数据去创建一个新的值,它是超级方便的。

二、Computed Properties In Action

example:

Person = Ember.Object.extend({
//these will be supplied by 'create'
firstname: null,
lastName: null fullName: Ember.computed('firstName', 'lastName', function () {
return this.get('firstName') + ' ' + this.get('lastName');
});
}); var ironMan = Person.create({
firstName: "Tony",
lastName: "Stark"
}); ironMan.get('fullName');//"Tony Stark"
  • 这里声明了一个function去作为一个计算的属性,参数告诉Ember它依赖于firstNamelastName属性。
  • 不管什么时候你访问fullname属性,这个function会被调用,并返firstname+lastname的值。

三、Chaining Computed Properties(计算属性链)

可以使用计算属性作为值去创建新的计算属性。

example:这里为上一个例子添加description计算属性,使用存在的fullName属性并添加一些其他的属性。

 Person = Ember.Object.extend({
firstName: null,
lastName: null,
age: null,
country: null, fullName: Ember.computed('firstName', 'lastName', function () {
return this.get('firstName') + ' ' + this.get('lastName');
}); description: Ember.computed('fullName', 'age', 'country', function () {
return this.get('fullName') + '; Age: ' + this.get('age') + '; Country:' + this.get('country');
});
}); var captainAmerica = Person.create({
firstName: 'Steve',
lastName: 'Rogers',
coutnry: 'USA''
}); captainAmerica.get('description');//"Steve Rogers; Age: 80; Country: USA"

四、Dynamic Updating

可计算的属性,默认情况下,观察它们所依赖的属性,并在调用时动态更新。让我们使用计算的属性来动态更新。

captainAmerica.set('firstName', 'William');
captainAmerica.get('description');//"William Rogers; Age:80; Country: USA"
  • 这个firstName的改变被计算的属性fullName观察到,它自己被description属性观察到。
  • 设置任何相关的属性都会通过任何依赖于它们的计算属性来传播变化,你已经创建了一条计算属性链。

五、Setting Computed Properties

当你设置计算的属性的时候你也可以定义Ember应该做什么。如果你试着设置计算的属性,它将会通过属性名被调用,你想设置的值和以前的值。

Person = Ember.Object.extend({
firstName: null,
lastName: null, fullName: Ember.computed('firstName', 'lastName', {
get(key) {
return this.get('firstName') + ' ' + this.get('lastName');
},
set(key, value) {
var [ firstName, lastName ] = value.split(/\s+/);
this.set('firstName', firstName);
this.set('lastName', lastName);
}
});
}); var captainAmerica = Person.create();
captainAmerica.set('fullName', "William Burnside");
captainAmerica.get('firstName');//William
captainAmerica.get('lastName');//Burnside  

Ember将会为settersgetters调用计算的属性,如果你想要使用计算的属性来作为一个setter,你需要去检查参数的个数来确定是否是被作为一个gettersetter调用。如果一个值是从setter返回的,它将会被缓存在属性的值里。

上一篇:Linux下几个常用的快捷键,真的很实用


下一篇:[Linux系统] (3)应用安装方式详解(编译安装、rpm包安装、yum安装)