What’s the best way to handle binding events on elements that will be refreshed with AJAX?
Is it better to use $(selector).live or similar methods for delegating events (on and delegate), or is it better to just re-bind the event handlers in $.ajax callbacks or $(document).ajaxComplete instead?
For the simple case, $(selector).live or equivalent works great, and seems like the right answer.
The tricky part is what to do inside a custom plug-in, where I’m creating a whole bunch of event handlers. I start running into problems in more complex cases where I want to register a handler on some other element that affects the one referenced by this.
For example, see jsFiddle: http://jsfiddle.net/f6QSY/2/
$.fn.myPlugin = function() {
$input = this;
var origSelector = this.selector;
$(document).on("click", "a#trigger1", function() {
$input.val('set from trigger 1');
});
$(document).on("click", "a#trigger2", function() {
$(origSelector).val('set from trigger 2');
});
}
$("input#newInput").myPlugin();
$("#wrapper").append("<input type='text' id='newInput'>");
<div id="wrapper">
<a href="#" id="trigger1">Trigger 1</a>
<a href="#" id="trigger2">Trigger 2</a>
</div>
In this code, the plugin is called on an input that is added dynamically and doesn’t exist yet (or is replaced via AJAX). The plugin sets up listeners on different elements that then impact the value of the input.
The trigger1 link doesn’t work because $input refers to a jQuery object with a selector that returned no elements at the time it was bound. The trigger2 link does work, by backing out the original selector for the input with this.selector and creating a new, fresh jQuery object in the event listener.
Is this approach of backing out the selector safe, or should I just call myPlugin again after updating the DOM?
My back-end is Java/JSF/PrimeFaces although that doesn’t matter too much.
“Better” is a loaded qualifier. Better in terms of what?
I will always choose delegation (using
.on())… where the listener is the nearest non-destroyed/replaced ancestor of any Ajax elements that need event binding.It’s possibly not ALWAYS going to be the most efficient in terms of computational cycles… a lot depends on the structure of your page and just how close that ancestor is. But it’s way way simpler to manage and decouples your Ajax call from your event binding.
To me, that’s “better”.
Sometimes what’s needed is not a direct answer to “how can I get my approach to work” but rather, a suggestion on how to tweak or retool your approach. In this case, I think caching a string of this.selector is creating a tight coupling where there doesn’t need to be one. Use classes, take advantage of DOM traversal (instead of IDs), and you will have a more re-usable product!
[update follows]
Not knowing exactly what your end goal is, here’s a pretty faked-up example of how I approach this sort of binding.
Full Fiddle: http://jsfiddle.net/QpXpD/2/
Reduced sample HTML:
CSS:
Reduced sample JS:
The plugin executes on an element which is an ancestor element that I will never destroy and which is expected to contain my clickable elements.
In the sample, the plugin is set to listen on
#wrapperfor any clicks on any element that has theclickableclass. Now it doesn’t matter if I remove anything from the DOM or add new elements to that listening container… if I click and the element has the classclickablethe function will execute. I do thefind()in the context of the click, not the context of the full document or any stored selector names. I’m clicking something, and I want to look inside of it for something else.Again, I don’t know what your end goal is with your finds, etc. But hopefully this helps illustrate how to use
.on()to avoid re-binding event handlers.[update 2]
The sample is still somewhat convoluted — it’s not clear why the input has to be added dynamically, or why you don’t just reverse the order of adding and then calling the plugin (it would then work!).
There is also too much of a reliance on element IDs. For something to be re-usable in a worthwhile way, you’re better off using classes. Here’s an update to your fiddle:
http://jsfiddle.net/f6QSY/4/
The triggers now have a class “trigger” (the ID is never used now).
the JS part: