I have been doing some reading up on jquery live event and am still kind of confused? What is the benefit to using it?
http://docs.jquery.com/Events/live
I know it is similar to bind but both of those events still seem off to me.
Just looking for some pointers.
Sometimes you have a set of elements when the page loads, like, say, edit links:
Now, maybe you have something like this with jQuery:
But what if you add a new element to this table dynamically, after the page has initially loaded?
When you click on ‘Edit’ on this new Item, nothing will happen because the events were bound on page load. Enter live. With it, you can bind the event above like this:
Now if you add any new
<a>elements with a class ofeditafter the page has initially loaded, it will still register this event handler.But how is this accomplished?
jQuery uses what is known as event delegation to achieve this functionality. Event delegation is helpful in this situation or when you want to load a large amount of handlers. Say you have a DIV with images:
But instead of 4 images, you have 100, or 200, or 1000. You want to bind a click event to images so that X action is performed when the user clicks on it. Doing it as you might expect…
…would then bind hundreds of handlers that all do the same thing! This is inefficient and can result in slow performance in heavy webapps. With event delegation, even if you don’t plan on adding more images later, using live can be much better for this kind of situation, as you can then bind one handler to the container and check when it is clicked if the target was an image, and then perform an action:
Since jQuery knows that new elements can be added later on or that performance is important, instead of binding an event to the actual images, it might add one to the div like in the first example (in reality, I’m pretty sure it binds them to the body but it might to the container in the example above) and then delegate. This
e.targetproperty can let it check after the fact if the event that was clicked/acted on matches the selector that you might have specified.To make it clear: this is helpful not only in the direct way of not having to rebind events, but it can be dramatically faster for a large amount of items.