There are 2 concerns normally, event handlers and plugins, which are two different things.
Part 1: Event Handlers
Event handlers are easy, because they act upon events, events behave identically no matter when the element as added. For this there's .live()
and .delegate()
, .live()
listens for events on document
and runs if an event comes from an element that matches the selector, let's take a table row for example:
$("tr").click(function() { ... });
This would find all current table rows, when it ran and bind a click
event handler to them, the same as .bind('click', function)
. Then there's .live()
, like this:
$("tr").live('click', function() { ... });
This listens for the click
event to bubble up to document
(this happens automatically, by default) and executes the handler...current and future elements behave the same way here. This means it works for both. Then there's .delegate()
which is a local version of .live()
like this:
$("#myTable").delegate('tr', 'click', function() { ... });
If you're just adding rows to #myTable
but not removing/adding the table itself, the same type of listener for bubbling events can sit there, instead of all the way up on document
, this means the event has to bubble fewer times before reaching the handler you want to execute.
Part 2: Plugins
Plugins are a bit trickier, because they take elements and do things with them (this is true for most plugins). You have two decent options here, either running the plugin when new elements yourself, for example loading via $.ajax()
or a shorthand version would look like this:
$.ajax({
//options...
success: function(data) {
//add elements
$("tr", data).myPlugin();
}
});
This finds new <tr>
elements, but only in a local context (in the returned HTML) and executes only on those elements. Alternatively, there's a plugin for this, less efficient, but usually not a noticeable difference on most pages. The .livequery()
plugin actively looks for and acts up new elements, the same code would look like this:
$("tr").livequery(function() {
$(this).myPlugin();
});
Either of these are valid solutions, just see which fits your needs better.