问题
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