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?
What are Computed Properties? In a nutshell, computed properties let you declare functions as properties. You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property. You can then use it the same way you would any normal, static property.
A computed property is a function that returns a value derived from other variables or expressions (even other computed properties) in your code. The difference between a computed property and a normal JavaScript function is that Ember. js treats your computed property function as if it were a real Ember.
Introduction to JavaScript Computed PropertyThe property name is derived from the value of the propName variable. When you access c property of the rank object, JavaScript evaluates propName and returns the property's value. Like an object literal, you can use computed properties for getters and setters of a class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With