标签:
一、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"
三、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"
五、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将会为setters和getters调用计算的属性,如果你想要使用计算的属性来作为一个setter,你需要去检查参数的个数来确定是否是被作为一个getter和setter调用。如果一个值是从setter返回的,它将会被缓存在属性的值里。
2.3 The Object Model -- Computed Properties
标签:
原文地址:http://www.cnblogs.com/sunshineground/p/5146144.html