Background
I have been using Backbone.js for some time and one aspect of it that impresses me is how it allows me to simplify, abstract and reuse DOM elements as 'views' . I have tried to read through some of the annotated source and am familiar with JQuery, but have little knowledge of how the DOM works on a deeper level.
Question
How does Backbone.JS tie DOM elements to views without assigning an id, class or other attribute to them?
i.e.
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
I love that Backbone does this and would like to know how it does it!
Source: Tips4all
In javascript, a variable can hold a reference (i.e a programmatic thing that "refers to") to some element of the DOM, which is just a Javascript object. Backbone makes sure that for a view, at least that element exists. For example, in jQuery, when you refer to the third item in your list:
ReplyDeletevar item3 = $('ul li').eq(2);
(It's a zero-offset list, the first item is at index 0, the third at index 2), you can now change the text from "Item three" to "Item three point one four one five nine" with ordinary jQuery DOM manipulators:
item3.text("Item three point one four one five nine");
Even though that list item doesn't have any particular class or ID attributes.
A backbone view's el field contains a constant reference to the parent element in which that view renders all of its stuff. Backbone uses the jQuery delegate event manager to attach a generic event handler to that one constant reference. Whenever an event happens within that DOM element or any of its children, the delegate catches the event, along with a reference to the specific DOM object within the parent el that created the event, and backbone uses some fairly standard jQuery magic to map that to an event handler in the view.
It is, indeed, very cool stuff.
I should add that the "constant"-ness of the el reference is, er, arguable. If you're attaching view logic to an existing HTML element, you do assign to the el once, in the view's initialize(). Javascript doesn't enforce any notion of constantness, but you should only directly assign to el (ie this.el = something()) if you're sure you know what you're doing.