Ember.js常用计算属性模式的简写

nic*_*des 7 javascript ember.js

在Ember.js中,我发现自己定义的计算属性如下所示:

someProp: function(){
  return this.get('otherProp');
}.property('otherProp')
Run Code Online (Sandbox Code Playgroud)

要么

someProp: function(){
  return this.get('otherObject.prop');
}.property('otherObject.prop')
Run Code Online (Sandbox Code Playgroud)

是否有更短的方法来编写遵循这些模式的计算属性?

mav*_*ein 12

经过一段时间的研究,你可以通过在Ember.computed.alias的帮助下做一些事情来干这个:

someProp: Ember.computed.alias("otherObject.prop")
Run Code Online (Sandbox Code Playgroud)

您也可以使用它alias来设置此属性.给定一个实现上面给出的属性的Ember对象,您可以:

obj.set("someProp", "foo or whatever"); // The set will be propagated to otherObject.prop
Run Code Online (Sandbox Code Playgroud)

链接到Ember.computed.alias的Ember Source


更新:Ember.computed.oneWay

最近,一个新的计算属性简写(oneWay)被添加到Ember,这也适用于此要求.不同之处在于oneWay速记仅适用于获取案例.因此,在创建对象时,这种速记比较复杂alias.

someProp: Ember.computed.oneWay("otherObject.prop")
Run Code Online (Sandbox Code Playgroud)

链接到Ember.computed.oneWay的Ember Source