Leaving jQuery behind: Backbone.Native
Backbone.Native is a simplified replacement for jQuery meant for developers who want to use Backbone but don’t need all the rest. It handles event delegation and element creation so that Backbone can work as expected, while encouraging developers to use the new native browser APIs. At 17.1K uncompressed, and only 1.5K minified and gzipped, Backbone.Native is also only 5% the size of jQuery, which is a significant reduction.
Go check it out on GitHub (Apache License 2)
How do you use it?
Backbone.Native is a drop-in replacement for Backbone’s jQuery usage, but it isn’t meant to be a complete substitute. The main goal of Backbone.Native is to let Backbone function with a minimum amount of dependencies while leaving as much as possible to browser APIs. That decision leads to certain changes that developers will have to take into consideration when writing code. With that in mind, let’s look at a few simplified examples of Backbone Views to demonstrate the main differences.
First, let’s compare a simple view that renders a set of subviews into existing child elements:
You’ll notice that we are using ‘this.el’ instead of ‘this.$el’. Since we don’t have jQuery’s collection behavior, developers should use the view’s element directly. Another change is that Backbone.Native does not provide a selector engine; instead, it relies on querySelectorAll. We also use Underscore’s ‘_.forEach’ to iterate because NodeLists do not have a standard forEach.
Next, let’s compare attaching an event handler for clicks on a child element:
The main change in this example is that Backbone.Native event handlers are passed the matching element as the second argument, rather than using ‘currentTarget’. Native DOM events are used rather than implementing a fake Event object, but because they are read-only, the ‘currentTarget’ property will reflect the element where the listener was bound, rather than the element matching the delegate selector.
How do you get started?
Just load backbone.native.js into your page after Backbone, and you should be ready to go.
We hope you find Backbone.Native useful! Please give us feedback on GitHub and take a look at the README for more information.