在Ember.js中,我发现自己定义了如下所示的计算属性:
someProp: function(){
return this.get('otherProp');
}.property('otherProp')
或
someProp: function(){
return this.get('otherObject.prop');
}.property('otherObject.prop')
是否有更短的方法来编写遵循这些模式的计算属性?
答案 0 :(得分:12)
经过一段时间的研究,你可以在 Ember.computed.alias 的帮助下完成以下任务:
someProp: Ember.computed.alias("otherObject.prop")
您也可以使用alias
来设置此属性。给定一个实现上面给出的属性的Ember对象,你可以这样做:
obj.set("someProp", "foo or whatever"); // The set will be propagated to otherObject.prop
Link to Ember Source for Ember.computed.alias
更新:Ember.computed.oneWay
最近,一个新的计算属性速记(oneWay
)被添加到Ember,这对于这个要求也是可行的。区别在于oneWay
简写仅适用于获取案例。因此,在创建对象时,这种速记比更复杂的alias
更快。
someProp: Ember.computed.oneWay("otherObject.prop")