Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js - how to 'get' computed properties

Tags:

ember.js

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?

like image 326
user1785797 Avatar asked Dec 15 '25 17:12

user1785797


1 Answers

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.

like image 129
louiscoquio Avatar answered Dec 19 '25 00:12

louiscoquio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!