2013-07-26 57 views
0

我有一個將在/products路徑下加載的產品列表,從那裏您可以導航到/products/:product_id下的單個產品。這是我的機型和路線:將額外的數據加載到仍在商店中的EmberData模型中

var Product = DS.Model.extend({ 
    page_title: DS.attr('string'), 
    image: DS.attr('string') 
}); 

var ProductComment = DS.Model.extend({ 
    contents: DS.attr('string') 
}); 

var ProductRoute = Ember.Route.extend({ 
    model: function(params) { 
    return App.Product.find(params.product_id) 
    }, 
    setupController: function(controller, model) { 
    controller.set('content', model); 
    } 
}); 

在產品頁面上,我想載入產品以及產品的註釋。當我使用外部Api時,我不能將註釋的ID加載到產品模型中。所以現在我想將註釋加載到ProductsController中。我嘗試了像這個SO中描述的,但它不起作用。我正在使用EmberDatas RESTAdapter。

回答

0

我想出瞭解決方案。在產品路線的modelAfter掛鉤中,使用this.get('product_comments').content.length檢查註釋是否已加載到模型中。如果不是,請使用App.ProductComment.find({product_id: this.id})加載數據並將它們存儲到模型中。

App.ProductRoute = Ember.Route.extend({ 
    afterModel: function(model) { 
    model.ensureComments(); 
    } 
}); 

Product = DS.Model.extend({ 
    page_title: DS.attr('string'), 
    image: DS.attr('string'), 
    product_comments: DS.hasMany('App.ProductComment'), 
    ensureComments: function() { 
    var productcomments = this.get('product_comments'); 
    if (!productcomments.content.length) { 
     App.ProductComment.find({product_id: this.id}).then(function(result) { 
     productcomments.pushObjects(result) 
     }); 
    } 
    } 
}); 
相關問題