Backbone.js Backbonejs中的嵌套视图,post&;评论关系
对象数组 从服务器接收数据Backbone.js Backbonejs中的嵌套视图,post&;评论关系,backbone.js,backbone-views,Backbone.js,Backbone Views,对象数组 从服务器接收数据 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_
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帖子评论系统的布局我会使用一个
评论列表视图
,由你的更新视图
拥有<代码>标记名:“ul”,类名:“发表评论”
然后拥有一个由CommentListView
拥有的CommentView
。CommentView的呈现不应该向DOM追加任何内容,而是返回其$el
CommentListView
会告诉每个要呈现的CommentView
,将每个$el
附加到CommentListView
的$el
对于容器,我将使用:
<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>
您是否遇到错误?你有什么问题?