For ajax web application that has many screens and navigations, to attach event handlers for div or links or buttons, we can code like :
//Using $.on inside Ajax success handler
$("#container").on("click", "#selector", function(event){
});
This approach will NOT work if container doesn't exists in the DOM. To make it work, will have to use document or body as the container, the performance may not be good.
There could be many lines of code in Ajax success handler. To organize better, can move the code to a function and call that function in Ajax success handler. But we have to make many register event functions for all permutations and combinations.
Register functions code cluttering.
If event handler was already registered, registering again will cause two even handlers. So we have to un-register and register (OR attach only if not attached already) - Not sure about performance problem.
Any alternatives ?
I am thinking of following :
- Maintain a map of container, target, and click event handler in one place for a module.
In ajaxComplete global event handler, if xhr.responseHTML has the container, attach event handler to target elements (attach only if not attached already).
$(document).ajaxComplete(function(e, xhr, settings){ for(ind in clickEventListeners){eventlistner = clickEventListeners[ind]; if($(eventlistner.container,xhr.responseHTML).length > 0){ $(eventlistner.target).on("click",function(){ eventlistner.processor(this); }); } } });
Pros : All event handlers documented in one place for a module. No code cluttering in for each ajax success handler.
Cons : I am not sure if any.
Please advise if any suggestions.