user1785797
user1785797

Reputation: 137

Ember.js - how to 'get' computed properties

I have successfully created and bound computed properties, but how can I get at them manually in other parts of my code?

App.Test = Ember.Object.extend(
   value: "1"
   unit: "INCH"

   display: (->
     value = this.get('value')
     unit = this.get('unit')
     return "#{value} #{unit}"
   ).property('value', 'unit')
)

How do I call the 'display' method in, say, a controller? The following shows what I thought would work...

myTest = App.Test.create()
displayValue1 = myTest.get('display')
displayValue2 = myTest.display()

displayValue1 just returns me an object, not a string. displayValue2 throws a 'no function found" error. So how do I access this property other than a binding?

Upvotes: 3

Views: 3066

Answers (1)

lcoq
lcoq

Reputation: 10726

Consider computed properties as properties, not method. Even if they contains a little bit of logic, they really are properties, so you should never call them as a method.

You can access them using the classic Ember.get method, as you can see below:

MyApp.myObject = Ember.Object.create({
    name: "foo",
    surname: "bar",
    aComputedProperty: function() {
        return this.get('name') + ' ' + this.get('surname');
    }.property('name', 'surname')
});

MyApp.myObject.get('aComputedProperty'); // => 'foo bar'

You can try this code in this JSFiddle.

Upvotes: 4

Related Questions