Is there a different between this.$el.html and this.$el.append when rendering templates? I'm totally new to js, backbone, etc. In the current project I'm working on, I see stuff like
this.$el.append(Project.Templates["template-library"](this.model))
in the outer view. In this case, this template is for a modal view. Then say the modal view has a row for each item to show in the modal view. Then for each of those rows, the template gets rendered like this:
this.$el.html(this.template({ libraries: libraries.toJSON() }));
Is there any difference between the two? And why append()
should be used in certain situations, and html()
in the other.
Is there a different between this.$el.html and this.$el.append when rendering templates? I'm totally new to js, backbone, etc. In the current project I'm working on, I see stuff like
this.$el.append(Project.Templates["template-library"](this.model))
in the outer view. In this case, this template is for a modal view. Then say the modal view has a row for each item to show in the modal view. Then for each of those rows, the template gets rendered like this:
this.$el.html(this.template({ libraries: libraries.toJSON() }));
Is there any difference between the two? And why append()
should be used in certain situations, and html()
in the other.
- I guess there is one (html) that just replace the content with the argument you got and the other (append) add the argument at the end. – Hugo Dozois Commented Apr 17, 2013 at 1:15
3 Answers
Reset to default 3For me it really es down to how you use your views' render
method.
Some people like to use render
as an extension of initialize
, in that they only use it once, when the view first appears on the page, and often call it from initialize
. With this style, you can safely use append
without worrying about accidentally adding elements twice, because the render won't get run twice.
Alternatively you can design render
to be used over and over again, whenever the view's element needs to change in some way. Backbone supports this style well, eg. this.model.on('change', this.render, this);
. For this style, append
would be annoying, as you'd constantly have to check whether elements already exist before append
-ing them. Instead html
makes more sense, because it wipes out whatever was there before.
With append a new element will be inserted into the $el
, while html will change the content of the $el
.
Using .append()
will allow you to add or append something to already existing objects. Rather using .html()
, it will change the entire object to new one.