Ember.js shorthand for common computed property pattern

二次信任 提交于 2020-01-14 08:13:18

问题


In Ember.js I find myself defining computed properties that look like this:

someProp: function(){
  return this.get('otherProp');
}.property('otherProp')

or

someProp: function(){
  return this.get('otherObject.prop');
}.property('otherObject.prop')

Is there a shorter way to write computed properties that follow these patterns?


回答1:


Having researched a little bit you could dry this a little up by doing the following with the help of Ember.computed.alias:

someProp: Ember.computed.alias("otherObject.prop")

You can use alias also to set this property. Given an Ember object which implements the property given above, you can do:

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

Link to Ember Source for Ember.computed.alias


Update: Ember.computed.oneWay

Recently a new computed property shorthand (oneWay) was added to Ember, which is also feasible for this requirement. The difference is that the oneWay shorthand only works in the get case. Therefore this shorthand is faster during object creation than the more complex alias.

someProp: Ember.computed.oneWay("otherObject.prop")

Link to Ember Source for Ember.computed.oneWay



来源:https://stackoverflow.com/questions/14965235/ember-js-shorthand-for-common-computed-property-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!