How do you dynamically create Backbone view elements?

chrisM picture chrisM · Apr 13, 2012 · Viewed 12.3k times · Source

I'd like to create some view elements in a Backbone js application dynamically. When a new view is initialized, I want it to insert the new element into the DOM, store the reference to the element in view.el, and delegate events as usual.

I understand that I can put in my html, and then setup a view with el: "#test" but this seems like overkill for modals and other views that aren't central to the web application. Is there a prescribed way to do this I'm missing in the docs? Am I just misunderstanding how views are supposed to work?

Answer

Derick Bailey picture Derick Bailey · Apr 13, 2012

A backbone view will generate an el for you, without you having to do anything. By default, it creates a <div>. You can generate any tag name you want, though. Once you have the view instantiated, implement a render method on the view, and populate the el with your HTML.


MyView = Backbone.View.extend({});

var v = new MyView();
console.log(v.el); // => "<div></div>"


// define your own tag, and render contents for it

MyTagView = Backbone.View.extend({
  tagName: "ul",

  render: function(){
    this.$el.html("<li>test</li>");
  }
});

var v2 = new MyTagView();
v2.render();
console.log(v2.el); // => "<ul><li>test</li></ul>"

It's common practice to use a template system to render your view's HTML, like Underscore.js template, Handlebars, or any of the other dozen or more template JavaScript template engines.

Once you have the content generated from the view, you need to stick it in to the DOM somewhere before it will be visible. This is usually done with jQuery or another plugin:

$("#some-element").html(v2.el);