Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop backbone from adding surrounding divs to a view?

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!

like image 254
egidra Avatar asked Aug 17 '11 17:08

egidra


3 Answers

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

like image 141
Caged Avatar answered Sep 20 '22 11:09

Caged


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

$('div#round-container', this.el).append(roundView.render().el.childNodes); 
like image 20
Sandeep Kashyap Avatar answered Sep 20 '22 11:09

Sandeep Kashyap


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

$('div#round-container', this.el).append(roundView.render().el.html());
like image 21
Pinelopi Kouleri Avatar answered Sep 21 '22 11:09

Pinelopi Kouleri