Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should a computed property be declared in a model or controller?

Having the following User model:

Sks.User = DS.Model.extend
  firstName: DS.attr("string")
  lastName: DS.attr("string")

where should the 'fullName' computed property be declared?

  fullName: Ember.computed(->
    firstName = @get("firstName")
    lastName = @get("lastName")
    firstName = ""  if firstName is `undefined`
    lastName = ""  if lastName is `undefined`
    lastName + " " + firstName
  ).property("firstName", "lastName")

Should it be in 'UsersController' or directly in the model? The Ember documentation says that fields used only across session, should be written in controllers. But the problem is I couldn't access 'fullName' in the Index template:

Sks.IndexController = Ember.Controller.extend
  needs: ['users']

Here, 'fullName' was inaccessible (declared in the controller)

{{#each user in controllers.users}}
  <li>{{user.fullName}}</li>
{{/each}}

But it is when it is in the model.

like image 581
wryrych Avatar asked Mar 27 '13 13:03

wryrych


People also ask

What is computed in Emberjs?

A computed property declares functions as properties and Ember. js automatically calls the computed properties when needed and combines one or more properties in one variable.

What is a computed property Ember?

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 is the difference between computed and methods in vue?

Computed Caching vs Methods Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies.

What is computed property in Javascript?

Computed properties allow you to dynamically choose what property in your object gets updated. It's important to give your input element a name attribute. The name attribute that you specify should match the property that you wish to update within the object. Retrieve the name and value from event.


1 Answers

In this case I think the model is the right place for the computed property because it only makes sense if you have the firstname and lastname attributes.

You can still put computed properties on the controller when it makes sense, but I imagine a property like "fullName" could be used in more than one place across your application (and having this in the controller would force you to duplicate the effort across different parts of the app)

like image 67
Toran Billups Avatar answered Oct 11 '22 13:10

Toran Billups