Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js shorthand for common computed property pattern

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?

like image 644
nicholaides Avatar asked Feb 19 '13 18:02

nicholaides


People also ask

What is computed property in Ember JS?

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.

What does computed mean in Ember?

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.

What is computed property in JavaScript?

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.


1 Answers

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

like image 155
mavilein Avatar answered Oct 08 '22 19:10

mavilein