Search code examples
javascriptbackbone.js

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!


Solution

  • 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