2014-12-03 110 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