Reputation: 366
In have a Users_Index view where I render all users. For each user I want to show a computed property. I do this in the corresponding ItemController. The code:
// app/controllers/users/index.js
import Ember from 'ember';
export default Ember.ArrayController.extend({
itemController: 'user'
});
// app/controllers/user.js
import Ember from 'ember';
export default Ember.ObjectController.extend({
myComputedProperty: function(){
// just example nonsense here
return this.get('name') + ' and ' + this.get('id');
}.property('name', 'id')
});
// app/templates/users/index.hbs
<ul>
{{#each}}
<li>
{{myComputedProperty}}
</li>
{{/each}}
</ul>
Now I have the User_Show view and want to use the computed property there as well. For sure I don't want to repeat the computed property code in the users/show controller
. Can anyone give me a hint what is the right way in Ember to share the code? A mixin? A component? Add the function to the user model (that sounds totally wrong)?
Upvotes: 1
Views: 183
Reputation: 2409
You can create a mixin like this:
App.ComputedProperty = Ember.Mixin.Create({
myComputedProperty: function(){
// just example nonsense here
return this.get('name') + ' and ' + this.get('id');
}.property('name', 'id')
}};
And then add it to your controller like this
App.UserController = Ember.ObjectController.extend(App.ComputedProperty, function() {
. . .
});
Give the API a read here.
Or, you can add the computed property to your User Model instead, like this:
App.User = DS.Model.extend({
name: DS.attr(
myComputedProperty: function(){
// just example nonsense here
return this.get('name') + ' and ' + this.get('id');
}.property('name', 'id')
});
Then you can access it every where you access a User Model.
Upvotes: 4