Reputation: 3011
I have a View that is already rendering a collection of posts:
Social.Views.StreamsIndex = Backbone.View.extend({
template: JST['streams/index'],
render: function(){
$(this.el).html(this.template({
entries: this.collection.toJSON()
}));
return this;
}
});
Now I have to comment on a post for which I have to render a different template for comment:
Social.Views.StreamsIndex = Backbone.View.extend({
template: JST['streams/index'],
events: {
'submit .comment_submit': 'comment_create'
},
comment_create: function(event) {
//create comment code
After creating I want to do something like this, so that it can render comment template
$("#comment).html(this.template1({
comment: comment
}));
}
});
Is it possible to render a two templates from the same view?
Edited: (Adding View)
Social.Views.StreamsIndex = Backbone.View.extend({
template: JST['streams/index'],
template1: JST['streams/comment'],
events: {
'submit .comment_submit': 'comment_create'
},
initialize: function(){
this.collection.on('reset', this.render, this);
this.model = new Social.Models.StreamsIndex();
this.model.bind('comment_createSuccess', this.comment_createSuccess);
},
render: function(){
$(this.el).html(this.template({
entries: this.collection.toJSON()
}));
return this;
},
comment_create: function(event) {
event.preventDefault();
event.stopPropagation();
post_id = $(event.currentTarget).attr("data-post-id");
href = $(event.currentTarget).attr('action');
comment_text = $("#comment_txt_"+post_id).val();
this.model.create_comment(href, post_id, comment_text); // this sends ajax request and post the comment to server
},
comment_createSuccess: function(data, post_id) {
this.$("#comment_for_post_"+post_id).append(this.template1({
comment: data
}));
}
});
Upvotes: 1
Views: 1040
Reputation: 8293
There's absolutely no problem here as templates are anyway not a part of Backbone's structure. I only have one remark, which is that you should use this.$
inside your view (it's a shortcut for this.$el.find
, so you'll only find descendants of your view's el).
So...
this.$('#comment').append(this.template1({ // changed to append to be used several times
comment: comment
}));
Edit:
About your context problem:
this.model.bind('comment_createSuccess', this.comment_createSuccess);
Here you can use the 3rd argument of bind
to set the context of the callback:
this.model.bind('comment_createSuccess', this.comment_createSuccess, this);
this
in your callback (comment_createSuccess
) will now be your view.
I personally would rather use Events#listenTo that would automatically bind the context:
this.listenTo(this.model, 'comment_createSuccess', this.comment_createSuccess);
Upvotes: 2