对象数组
从服务器
接收数据var Updates = [
{"post_id":"1","post_desc":"This is my first post",
"comments":[{"id":1,"comment":"some comments","like":7},
{"id":9,"comment":"some comments","like":3}
]
},
{"post_id":"2","post_desc":"This is my second post",
"comments":[{"id":5,"comment":"some comments","like":5}]
}]
型号:
var Update = Backbone.Model.extend({
defaults:{
photo: "default.png"
}
});
收集:
var latestUpdates = Backbone.Collection.extend({
model: Update
});
单一视图:
var UpdateView = Backbone.View.extend({
tagName: "div",
className: "post-container",
template: $("#postTemplate").html(),
render: function () {
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
主视图:
var UpdatesView = Backbone.View.extend({
el: $("#postContainer"),
initialize: function () {
this.collection = new latestUpdates(Updates);
this.render();
},
render: function () {
var that = this;
_.each(this.collection.models, function (item) {
that.renderUpdates(item);
}, this);
},
renderUpdates: function (item) {
var updateView = new UpdateView({
model: item
});
this.$el.append(updateView.render().el);
}
});
//create app instance
var wallUpdates = new UpdatesView();
如何在每个帖子下呈现评论部分? 试图实现类似于facebook post-comment system的布局
答案 0 :(得分:0)
我使用CommentListView
拥有的UpdateView
。 tagName: "ul", className: "post-comments"
然后CommentView
拥有CommentListView
。 CommentView的渲染不应该向DOM附加任何内容,而是返回其$el
。
CommentListView
会告诉每个CommentView
要呈现,并将$el
的每个CommentListView
附加到$el
的{{1}}。< / p>
对于容器,我会使用:
<div class="post-container" data-post-id="<%= YourPostId %>">
<div class="post-body">
<!--Your post can go in here-->
</div>
<ul class="post-comments">
<!--Append your comments in here-->
</ul>
</div>