0

I have a list of products that will be loaded under the /products route, from there you can navigate to a single product under the /products/:product_id. This is my models and the route:

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

On the product page I want to load the products and additionally the comments for a product. As I use an external Api I cant load the id of the comments into the product model. So now I want to load the comments in to the ProductsController. I tried like described in this SO but it doesn't work. I'm using EmberDatas RESTAdapter.

4

1 回答 1

0

I came up with solution. In the modelAfter hook of the products route, check if the comments are loaded into the model using this.get('product_comments').content.length. If not, load the data using App.ProductComment.find({product_id: this.id}) and store them into the model.

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)
      });
    }
  }
});
于 2013-08-04T13:19:34.367 回答