我有一个带有评论列表的待办事项模板。每个待办事项在本地存储中都有一个评论数组“评论”。我获取所有待办事项,遍历每个待办事项的“评论”数组,我希望将所有评论分配给相应的待办事项。如何附加到正确的评论列表?
目前我得到这样的输出:
Post1
Comment1_Post1
Comment2_Post1
Comment1_Post2
Comment2_Post2
Post2
Comment1_Post2
Comment2_Post2
Edit1:新的 CommentCollectionView
render: function() {
this.$el.html(this.template());
var commentList = this.$("ul.comment-list");
this.collection.each(function(comment) {
var commentView = new CommentView({model: comment});
commentList.append(commentView.render().el);
});
return this;
},
HTML:
<body>
<div class="content">
<ul class="todos-list"></ul>
</div>
// Templates
<script type="text/template" id="todo-template">
<label class="todo-content"><%= content %></label>
<ul class="comment-list" style="margin-left: 2em"></ul>
</script>
<script type="text/template" id="comment-template">
<label class="comment-content"><%= content %></label>
</script>
待办事项视图:
var TodoView = Backbone.View.extend({
tagName: "li",
template: _.template($("#todo-template").html()),
events: {
"click button.addComment": "addComment"
},
initialize: function() {
_.bindAll(this, "render");
this.model.bind("change", this.render);
var commentsArray = this.model.get("comments");
var commentCollection = new CommentCollection();
commentCollection.add(commentsArray);
var commentCollectionView = new CommentCollectionView({model: commentCollection});
}
});
评论收藏视图:
var CommentCollectionView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render", "appendItem", "addAll", "renderComment");
this.model.bind("reset", this.addAll);
this.model.bind("change", this.render);
this.model.bind("add", this.appendItem);
this.model.trigger("reset");
},
addAll: function() {
this.model.each(this.appendItem);
},
appendItem: function(comment) {
var commentView = new CommentView({model: comment});
$("ul.comment-list").append(commentView.render().el);
}
});