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属性并添加一些其他的属性。

 1 Person = Ember.Object.extend({
 2     firstName: null,
 3     lastName: null,
 4     age: null,
 5     country: null,
 6 
 7     fullName: Ember.computed('firstName', 'lastName', function () {
 8         return this.get('firstName') + ' ' + this.get('lastName');
 9     });
10 
11     description: Ember.computed('fullName', 'age', 'country', function () {
12         return this.get('fullName') + '; Age: ' + this.get('age') + '; Country:' + this.get('country');
13     });
14 });
15 
16 var captainAmerica = Person.create({
17     firstName: 'Steve',
18     lastName: 'Rogers',
19     coutnry: 'USA'20 });
21 
22 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返回的,它将会被缓存在属性的值里。

原文地址:https://www.cnblogs.com/sunshineground/p/5146144.html