2013-07-26 56 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) 
     }); 
    } 
    } 
}); 
相关问题