如何使用Marionette的ItemView渲染集合?

问题描述 投票:3回答:1

我正在尝试使用Backbone.Marionette.ItemView从API(JSON)呈现响应。不知道为什么它不起作用。

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

这是把手模板:

<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>

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

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

此外,我试图console.log视图,看起来模型在那里。

javascript backbone.js handlebars.js marionette
1个回答
3
投票

这个答案是针对Marionette v2.4.7量身定制的。 LayoutViewItemView合并,并在View重新命名为v3.0.0


来自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();
  },
});

木偶甚至提供collectionEvents

var PostView = Marionette.ItemView.extend({
  // ...snip...
  collectionEvents: {
    "sync": "render"
  }
  // ...snip...
});
© www.soinside.com 2019 - 2024. All rights reserved.