我正在做一个基本上像Facebook墙一样工作的应用程序。
本质上是帖子和评论。
它正在工作,但为了呈现 CommentView,我在帖子模板中使用了与此类似的代码
<div class="wall-post">
<div class="wall-post-content">${PostContent}</div>
<div class="wall-post-comments" id="wall-post-comments-${PostId}"></div>
</div>
然后我像这样使用该帖子的评论区域的 id。
var comment_view = new PostCommentView({ model: post.get("Comments") });
this.$('#wall-post-comments-'+ post.get("PostId")).append($(comment_view.render()));
这有效,但有些事情告诉我,我不应该手动绑定我自己的 ID。我觉得我应该用这个做一些聪明的事情。
谁能指出我正确的方向。
我正在使用BackBone Relational 来管理关系。
//编辑
根据要求,更多的实施
删除了一些与点击偶数和功能相关的功能,因为我认为它们与我的问题无关。
PostModel = Backbone.RelationalModel.extend({
urlRoot: '/api/post',
idAttribute: 'PostId',
relations: [{
type: Backbone.HasMany,
key: 'Comments',
relatedModel: 'CommentModel',
reverseRelation: {
key: 'Post',
includeInJSON: 'PostId'
}
}]
});
CommentModel = Backbone.RelationalModel.extend({
urlRoot: '/api/comment',
idAttribute: 'PostId'
});
PostCollection = Backbone.Collection.extend({
url: '/api/post',
model: PostModel
});
PostListView = Backbone.View.extend({
tagName: 'div',
className: 'PostListView',
initialize: function(){
_.bindAll(this, 'render', 'render_thread_summary', 'on_submit', 'on_thread_created', 'on_error');
this.model.bind('reset', this.render);
this.model.bind('change', this.render);
this.model.bind('add', this.render_thread_summary);
},
template: $('#wall-post-template').html(),
render: function() {
$(this.el).html($(this.template).tmpl(this.model.toJSON()));
this.model.forEach(this.render_thread_summary);
return $(this.el).html();
},
render_thread_summary: function(post) {
var comment_view = new PostCommentView({ model: post.get("Comments") });
this.$('#wall-post-comments-'+ post.get("PostId")).append($(comment_view.render()));
}
});
PostCommentView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render', 'on_click');
this.model.bind('change', this.render);
},
template: $('#wall-comments-template').html(),
render: function() {
var html = $(this.el).html($(this.template).tmpl(this.model.toJSON()));
return html;
}
});
我刚刚开始深入研究 Backbone(并且还没有对 Backbone Relational 做任何事情),所以考虑到这一点,这是我的 2 美分:
- Backbone 为其模型定义了 id,因此无需定义自己的 id attr。如果检查模型实例,即使 impl 中未明确定义,也会看到其 id。
- 在我看来,您缺少由单个评论模型组成的评论集合。然后在视图中适当地附加模型事件。这样你就不必手动管理评论视图渲染(这一切都由 Backbone 根据事件触发器完成)。
如果您还没有研究过 BB 示例 Todos 应用程序,我建议您看一看 - 这应该可以帮助您设计评论模型并更好地查看。
待办事项.js
待办事项应用程序 - 使用Fire/ChromeBug检查代码
希望这有帮助。
我严重低估了this.el引用。页面上的大多数内容通常不需要使用 id,因为在视图中,您只需引用 $(this.el),然后从页面的该部分引用。$(".className", this.el) 将在页面上的项目中选择任何类。EL 实质上是对页面上呈现视图的区域的引用。一旦你掌握了窍门,它真的很干净。