我正在做一個基本上像Facebook牆一樣工作的應用程序。在backbone.js中爲孩子們使用手動ID綁定是否正確
基本上是文章和評論。
它的工作,但爲了呈現評論查看,我用我的帖子模板
<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關係來管理關係。
//編輯
按照要求一些實施
//一些功能與點擊去除脣上和功能,因爲我不認爲這涉及到我的問題。
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;
}
});
爲了確認,我還沒有真正理解這個。 – 2012-04-18 18:10:07
你可以發佈PostCommentView及其模型的實現嗎? – rtorres 2012-04-18 20:44:27
發表了,感謝您抽出時間:)您可以看到我的代碼基本上來自迄今爲止的骨幹關係教程。 – 2012-04-18 21:46:55