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.
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 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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With