2015-04-02 55 views
1

我不明白以下哪種方式在Ember工作流程中更有意義。什麼是清潔劑?如何在路線中使用`model`?

最好有一個model像這樣的代碼?

應用程序/路由/ index.js

import Ember from 'ember'; 

export default Ember.Route.extend({ 
    model: function() { 
    return { 
     categories: this.store.find('category'), 
     products: this.store.find('product') 
    }; 
    } 
}); 

或者是更好地在此代碼不能使用model都不像?

應用程序/路由/ index.js

import Ember from 'ember'; 

export default Ember.Route.extend({ 
    categories: function() { 
    return categories: this.store.find('category') 
    }, 
    products: function() { 
    return products: this.store.find('product') 
    } 
}); 

或者是兩種方式很好,我不應該擔心嗎?

回答

1

除語法外,兩種方式都沒有任何顯着差異。第二部分要注意的一點是,你有一個語法錯誤。不需要categories :部分,您可以直接從store.find返回承諾。此外,您應該使用.property()將這兩個函數編入computed properties,以便可以按照模型的處理方式進行處理。現在他們只是功能,所以在大多數情況下他們不能被觀察到。這裏是你的第二個選項應該什麼樣子:

categories: function() { 
    return this.store.find('category'); 
}.property(), 

products: function() { 
    return this.store.find('product'); 
}.property() 

我與@panta的第一種方式是「灰燼」,雖然辦法達成一致。當你只想獲得模型的相關部分,而不是整個事物時,我可以看到第二種方法是有用的。

假設您的模型是一個倉庫,其中包含產品和產品類別,但也包含名稱,地址等內容。

{ 
    name: "My Warehouse", 
    size: 10, 
    address: "123 St" 
    // ... other properties 
    products: // ... 
    categories: // ... 
} 

然後,你可以方便地從商店獲得只有你實際需要在一個特定的控制器(當您加載實際倉庫模型別處)中的數據:

categories: function() { 
    return this.store.all('category'); // use .all to get all records currently in the store 
}.property(), 

products: function() { 
    return this.store.all('product'); // use .all to get all records currently in the store 
}.property() 
2

第一個代碼絕對是正確的「Ember方式」。我什至不知道你將如何使用你的第二個代碼

{{#each category in model.categories}}<!-- use category -->{{/each}} 

categoriesproducts將出現在您的控制器的模特屬性,所以從您的模板,你可以做這樣的東西。控制器根本無法聯繫到他們。