一个视图中的多个资源

时间:2013-08-04 13:40:38

标签: backbone.js marionette

我想显示图片列表及其各自的评论。像:

Image url                    | Format        | Comments
http://example.com/img.jpg   | 1280x420      | [Comment 1], [Comment 2] ...show all  ...show all  
http://example.com/img2.jpg  | 630x590       | [Comment 1], [Comment 2] ...show all  

我有两个资源:/ images和/ comments / {image_id}

为每个图像获取注释以便能够在同一行上显示它们的建议方法是什么?木偶有帮助吗?

3 个答案:

答案 0 :(得分:0)

据我所知,木偶没有这样的帮助。我认为你可以使用简单的东西:

var ImageComments = Backbone.Collection.extend({
  initialize: function(models, options) {
    options || (options = {});
    this.imageId = options.imageId;
    Backbone.Collection.prototype.initialize.apply(this, arguments);
  },

  urlRoot: function() {
    return 'comments/' + this.imageId;
  }
});

var id = 1,
    image = new Image({ id: id }),
    comments = new ImageComments(null, { imageId: id });

$.when(image.fetch(), comments.fetch()).done(function() {
  // .. do your things with image & comments 
});

这描述了一个简单的情况,如果在您的应用程序中常用,您可能希望实现自己的获取方法(例如,对于图像,也将获取注释)或使用Backbone-relationalBackbone-associations等插件

答案 1 :(得分:0)

答案 2 :(得分:0)

在我看来,这些看起来是使用关系模型的好地方。 Backbone不支持这些开箱即用,所以你需要一个插件。请查看Backbone-Relationalsupermodel.js。与默认实现相比,这些项目提供了更好的模型嵌套形式。从那里,使用嵌套的复合视图来渲染集合。