最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - this.$el.html vs this.$el.append - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question edited Apr 17, 2013 at 1:15 Stuart M 11.6k6 gold badges47 silver badges59 bronze badges asked Apr 17, 2013 at 1:13 CrystalCrystal 29.6k64 gold badges229 silver badges403 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 3

For 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.

发布评论

评论列表(0)

  1. 暂无评论