views:

27

answers:

2

Hi,

So I came across a piece about the difference between jQuery's bind() and live() - http://msdn.microsoft.com/en-gb/scriptjunkie/ee730275.aspx - (Live and Let Die section)

The bind function registers the event handlers with the actual DOM elements that were selected, but the live function registers the event handlers on the document.

I've used both functions so I get the difference in practice i.e. .live('click', function() {..}); will fire on a JS injected node, while the bind equivalent wouldn't.

What I'm not aware of is the relationship/difference between document and DOM. Can anyone enlighten me please?

Thanks, Denis

A: 

It's not a difference between document and DOM. It's a difference between the document object and the individual DOM element objects. The live function watches for all events in the document and if the object that triggered the event matches the selector, it will call the handler. On the other hand, the bind function watches for events triggered by a specific element object (the handler is attached to that specific object). If you delete and re-create the element, it will be a different object, and will not have the event handler attached. This implies that you have to know what the object is at the time you run bind.

Lukáš Lalinský
+2  A: 

The 'document' you refer to is the window.document variable browsers expose in JavaScript, and is the root node of the DOM. Remember that the DOM, like your HTML document, is a hierarchy of elements.

The way events work in DOM is they pass from the top of the hierarchy, the document, down to the element in question, allowing each element in between to capture the event. They then make a second pass back up the hierarchy, called bubbling. The jQuery methods you mention both hook in to the bubbling phase of events.

By hooking into the click event on the document, you get to see all click events on all elements, because they all pass through the root node, the document. jQuery then filters what you need based on your selector.

If you simply use bind, you'll hook into the events for the given elements that exist at that given time. If you later add new elements to the page, they won't have the callback bound to them.

Shtééf
+1 well said. Maybe you could've written a bit more about the DOM, because it's not just a hierarchy of elements, it is an in memory representation, which exposes an interface that allows you to interact with the actual page.
galambalazs