如何用Marionette的ItemView渲染一个集合?

时间:2017-12-11 20:36:50

标签: javascript backbone.js handlebars.js marionette

我尝试使用Dryscrape从API(JSON)呈现响应。不知道为什么它不起作用。

我正在使用牵线木偶v2.4.7(故意);

以下是把手模板:

Backbone.Marionette.ItemView

以下是我的完整 app.js (此文件中的所有Backbone逻辑);

<script id="feed-post" type="text/x-handlebars-template">
  {{#each posts}}
    <a href="#"><img src="{{author.image_url}}" alt=""></a>
    <a href="#"><p>{{author.name}}</p></a>
    <span>TODO TIMESTAMP</span>
    <p>{{body}}</br>{{topic_type}}</p>
  {{/each}}
</script>

此外,我尝试// Model var Post = Backbone.Model.extend({ defaults: { authorPic: 'Unknown', authorName: 'Unknown', timestamp: 'Unknown', body: 'Not available', comments: '0' } }); // Collection var Posts = Backbone.Collection.extend({ model: Post, url: 'http://localhost:4321/blogposts', initialize: function(){ this.fetch(); } }); // View var PostView = Marionette.ItemView.extend({ el: '#content', template: Handlebars.compile($("#feed-post").html()), }); //Config var chunkPosts = new Posts(); var myview = new PostView({collection: chunkPosts}); 视图,看起来模型就在那里。

https://i.imgur.com/wg4NIZr.png

1 个答案:

答案 0 :(得分:3)

此答案适用于Marionette v2.4.7。 LayoutViewItemView已合并,并在v3.0.0重新命名为View

来自doc on ItemView

  

渲染此视图会将someCollection集合转换为   要使用的模板的items数组。

您在模板中使用posts,而文档说它将被称为items

作为参考,这里是ItemView source中执行此操作的确切代码:

// Serialize the model or collection for the view. If a model is
// found, the view's `serializeModel` is called. If a collection is found,
// each model in the collection is serialized by calling
// the view's `serializeCollection` and put into an `items` array in
// the resulting data. If both are found, defaults to the model.
// You can override the `serializeData` method in your own view definition,
// to provide custom serialization for your view's data.
serializeData: function() {
  if (!this.model && !this.collection) {
    return {};
  }

  var args = [this.model || this.collection];
  if (arguments.length) {
    args.push.apply(args, arguments);
  }

  if (this.model) {
    return this.serializeModel.apply(this, args);
  } else {
    return {
      items: this.serializeCollection.apply(this, args)
    };
  }
},

最后几行显示,对于集合,将返回一个items作为唯一属性的新对象。

提到您可以覆盖serializeData函数more information and examples are available in the doc

您仍然需要在视图上调用render,因为收藏集fetch是异步的,您不会开箱即用,所以您应该连接一个监听器

首先,不要在集合的initialize中获取它,这使得该集合对于任何其他用例都毫无用处。

var Posts = Backbone.Collection.extend({
  model: Post,
  url: 'http://localhost:4321/blogposts',
});

侦听集合sync事件,然后在视图中获取。

var PostView = Marionette.ItemView.extend({
  el: '#content',
  template: Handlebars.compile($('#feed-post').html()),
  initialize: function () {
    this.listenTo(this.collection, 'sync', this.render);
    this.collection.fetch();
  },
});

Marionette甚至提供collectionEvents

var PostView = Marionette.ItemView.extend({
  // ...snip...
  collectionEvents: {
    "sync": "render"
  }
  // ...snip...
});