Stop backbone from adding surrounding divs to a vi

2019-03-09 17:46发布

I am using Handlebars.js as a templating tool for my Backbone.js app. My render functions in my views usually look like the following:

  var source = $("#round").html();
  var template = Handlebars.compile(source);
  var context = JSON.parse(JSON.stringify(this.model));
  var html = template(context);
  $(this.el).html(html);
  return this;

The above is appended to the main app view through the following code(this is the code that calls the above code):

$('div#round-container', this.el).append(roundView.render().el);

My Handlebars template handles all of the styling and layout, so I leave the "el" element of a view blank. Backbone.js automatically adds surrounding div tags around the Handlebars template. I assume this is because the "el" element is blank. Is there a way to prevent the addition of the surrounding div tags? Thanks!

3条回答
贼婆χ
2楼-- · 2019-03-09 18:19

Another easy way is to append the childnodes of the rendered element instead

$('div#round-container', this.el).append(roundView.render().el.childNodes);
查看更多
闹够了就滚
3楼-- · 2019-03-09 18:27

What's happening is this.el is created on the fly because it was never explicitly set by you. You have two options:

  1. You should specify the element you want to create with tagName, className and/or id and let backbone create that for you.

  2. In render you should set this.el to the contents of your handlebars template. So you would have this.el = $(template(context)).

The docs have an expanded explanation - http://documentcloud.github.com/backbone/#View-el

查看更多
爷的心禁止访问
4楼-- · 2019-03-09 18:41

Or append the html of the rendered element, e.g.:

$('div#round-container', this.el).append(roundView.render().el.html());
查看更多
登录 后发表回答