2014-12-03 98 views
0

在拥有一个Users_Index视图,其中呈现所有用户。对于每个用户我想显示一个计算属性。我在相应的ItemController中执行此操作。代码:共享计算出的财产代码

// 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> 

现在我有User_Show看法,并希望有使用计算性能为好。当然,我不想在users/show controller中重复计算出的财产代码。任何人都可以给我一个提示什么是正确的方式在Ember分享代码?混合?一个组件?将该功能添加到用户模型(听起来完全错误)?

回答

3

您可以创建一个混合是这样的:

App.ComputedProperty = Ember.Mixin.Create({ 
    myComputedProperty: function(){ 
     // just example nonsense here 
     return this.get('name') + ' and ' + this.get('id'); 
    }.property('name', 'id') 
}}; 

然后将其添加到您的控制器这样

App.UserController = Ember.ObjectController.extend(App.ComputedProperty, function() { 
    . . . 
}); 

给这个API读here

或者,你可以计算的属性添加到您的用户模型,而不是像这样:

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') 
}); 

然后在那里您可以访问用户模型,您可以访问它的每一个。

+0

在您看来,最简洁的方式来实现它?混合或添加到模型? – 2014-12-04 13:35:52

+0

如果你只需要一个模型,那么模型可能更容易。如果你在多个控制器上需要它,那么可能是混合。 – NicholasJohn16 2014-12-04 18:50:16