Property computed when use?


#1

Hi, i’m new here. I don’t know when use the property computed in view,model or controller… Thanks *Note: My english is more o less sry.


#2

I think the basics are explained in http://emberjs.com/guides/object-model/what-do-i-use-when/ and http://emberjs.com/guides/object-model/computed-properties/


#3

Yes, I read many times that, but I do not understand, and i was looking for examples online for example.


#4

The computed properties are not very conveniently documented.

Here are a couple code examples I fired up that might be useful.

http://jsbin.com/eTeqEyO/1/

http://jsbin.com/URuJOCa/1/

Also you should read up on Enumerable types supported in Ember JS. In a lot of cases you will be looping over a collection of model objects to derive a computed value. So understanding the enumerables will make it easier to write your code.

http://emberjs.com/guides/enumerables/

http://emberjs.com/api/classes/Ember.Enumerable.html

In its basic form a computed property is just a function that performs some logic and attempts to filter, collect, or parse other data that may be available to your application.

  highGPA: function() {
    if (this.get('gpa') > 3.5) {
      return true;
    } else {
      return false;
    }
  }.property('gpa') 

A computed property could just be a simple function.

  randomNumber: function() {
    var min = 1;
    var max = 100;
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }.property()

Look at the second example above, you will note that I use this random function in two places. Once in the model to generate a random number representing the student’s “room number”, and also in the controller to just output a random number in the template. The “classRoom” function is run for every instance of the model. If this is an expensive function you should be aware of potential performance implications.

Most of the time Ember tries to cache the computed property values and will only run the function when data changes. This is why you have to pass a property string to the

.property() 

function. For example

.property('gpa') 

means that this function will only change is one of the GPAs in one of the models changes.

Also, before you go writing a bunch of custom computed functions for common comparisons, you should be aware that Ember has a bunch of functions built in that can be useful for common comparison logic.

Here are a couple good reads on the topic.

http://coderberry.me/blog/2013/07/07/useful-functions-in-the-ember-namespace/

http://eviltrout.com/2013/07/07/computed-property-macros.html

Hope this helps.