Attach view to existing element in Backbone

You can attach a view to an existing element in Backbone.js. By default Backbone will create a new div for your view and is accessible in the el and $el properties.

To attach to an existing element you can:

  1. Set the el property in the definition of the view
  2. Set the el property when constructing a new view

With both techniques you can pass a jQuery selector, a jQuery object, or a function that returns a jQuery object.

// In view definition as selector
var MyView = Backbone.View.extend({  
  el: '.myview-container'
});

// In view definition as object
var MyView = Backbone.View.extend({  
  el: $('.myview-container')
});

// In view definition as function
var MyView = Backbone.View.extend({  
  el: function() {
    return $('.myview-container');
  }
});

// Passed as jQuery selector
var view = new MyView({  
  el: '.myview-container'
});

// Passed as jQuery object
var view = new MyView({  
  el: $('.myview-container')
});

// Passed as function
var view = new MyView({  
  el: function() {
    return $('.myview-container');
  }
});
comments powered by Disqus