Skip to content

Using Backbone without jQuery

Adam Krebs edited this page Apr 7, 2014 · 15 revisions

With the latest changes from #3003, Backbone is now even further decoupled from jQuery. You can use your favorite non-jQuery DOM manipulation library with Backbone.View, or even forgo a DOM manipulation entirely. Backbone.View now exposes a hooks that allow a View "adapter" to easily overwrite a few key Backbone.View methods that leave the rest of the public interface mostly the same.

For most users, the changes should be minimal. If you like using jQuery please by all means continue using it. If you're interested in using something other than jQuery with your project, take a look at Backbone.D3View for D3-backed Views, and Backbone.NativeView for going full native. You can also use a server-side DOM library like jsdom or cheerio as in this gist example.

View Hooks:

There are 8 total overridable methods:

  • $ for view-scoped element lookup. Takes a string selector and returns an array-like object (i.e. an object with a numeric length property, like an NodeList, an Array, or a jQuery context) for easy iteration. See Backbone.View and Backbone.NativeView implementations.
  • _createElement creates an element given a tagName. Useful for out-of-browser DOM creation (for instance server-side rendering). Backbone.View and Backbone.NativeView use the same method.
  • _removeElement to remove the view's element from the DOM. Backbone.View and Backbone.NativeView.
  • delegate to add a single event listener to the view's this.el property, with the benefit of easy bookkeeping for later event removal. Backbone.View and Backbone.NativeView.
  • undelegate to remove a single event listener, the inverse of delegate. The selector and listener arguments are optional. Backbone.View and Backbone.NativeView.
  • undelegateEvents to remove all events added by delegate. Backbone.View and Backbone.NativeView.
  • _setElement sets the view's this.el property from a string of HTML, a string Backbone.View and Backbone.NativeView.
  • _setAttributes applies a hash of attributes to the element. Backbone.View and Backbone.NativeView.

For Plugin Authors:

Since we can no longer rely on the existence of the jQuery-friendly interface of view.$el to be present on all Views, Backbone.View exposes two new hooks for event delegation, view.delegate and view.undelegate. It also stipulates that the return value from view.$ be an array-like object (a 0-indexed element list with a numeric length property, like an Array, a NodeList, or a jQuery context). You should iterate over the return value of view.$ with _.each and use native element methods on the results:

_.each(view.$('.title'), function(el) {
  el.classList.add('active');
});