I have three different view templates: “post”, “comment”, “add new comment”. The main template is “post”. I need to find out how to place “comments” and “add new comment” templates into theyr divs in the “post” template. Or any other methods to make this structure:
- post
- comments
- add new post form
- post
...
It is similar to facebook wall
Javascript for Backbone:
// Post View
var PostView = Backbone.View.extend({
template: $("#post").html(),
...
render: function () {
var tmpl = _.template(this.template);
var thisPost = this.model.toJSON();
this.$el.html(tmpl(thisPost));
}
});
var postView = new PostView();
postView.render();
// Comments List
var CommentsListView = Backbone.View.extend({
el: '#comments', // how to place it to #comments div in "post" template? This line doesn't work
...
addNewCommentForm: function (post_id) {
var tmpl = _.template($("#addCommentTemplate").html());
this.$('#addNewComment').append(tmpl()); // How to place it to #addNewComment div in "post" template? This line doesn't work
}
});
HTML:
<script id="post" type="text/template">
<%= text %>
<div id='comments'>...</div>
<div id='addNewComment'>...</div>
</script>
There are a number of things wrong with your code. The first being that you aren’t actually putting the
PostView.elinto the DOM. ThroughPostView.render(), you are populatingPostView.$eland subsequentlyPostView.el, but you’re not actually putting it into the page (DOM). Additionally, by setting theelonCommentsListView, you’re not really doing anything there. If you wanted to set theelto an existing element, then you would do something like this:el: $('#comments'). Or if you want to render theCommentsListViewdynamically and inject it into the DOM, then you would want to just make the element have an id of ‘comments’ by doing defining the id property like so:id: 'comments'. Those are just the two most obvious problems with the code. I got a semi-working example running here: http://codepen.io/jayd3e/pen/hAEDv.