I’m doing an app that basically works like the facebook wall.
Essentially Posts and Comments.
It’s working, but in order to render the CommentView, I’m using code similar to this in my Post Template
<div class="wall-post">
<div class="wall-post-content">${PostContent}</div>
<div class="wall-post-comments" id="wall-post-comments-${PostId}"></div>
</div>
Then I use the id of the comment area for that post like this.
var comment_view = new PostCommentView({ model: post.get("Comments") });
this.$('#wall-post-comments-'+ post.get("PostId")).append($(comment_view.render()));
This works, but something tells me I shouldn’t be manually binding against my own ID. I feel I should be doing something clever with this.el ?
Can anyone point me in the right direction.
I’m using BackBone Relational to manage the relationships.
//EDIT
As requested some more of the implementation
//Some functions relating to click evens and functionality removed, as I don’t think they relate to my question.
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;
}
});
I was greatly underusing the this.el reference. There is no need to generally use id’s for most things on the page, as within a view you can just reference $(this.el) and then reference from that part of the page. $(“.className”, this.el) will select any class’s with in the item on the page. el is essentially a reference to the area on the page where the view was rendered to. It’s really clean once you get the hang of it.