我正在尝试使用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
视图,看起来模型在那里。
这个答案是针对Marionette v2.4.7量身定制的。 LayoutView
和ItemView
合并,并在View
重新命名为v3.0.0。
渲染此视图会将
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...
});