JQuery автоматически регистрирует обработчики событий для действий пользователя над элементами, которые добавляются в DOM по ответу Ajax

Для веб-приложения ajax, которое имеет много экранов и переходов, чтобы прикрепить обработчики событий для div, ссылок или кнопок, мы можем написать код:

//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.

Есть альтернативы?

Я думаю о следующем:

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);
      });
  }
 }
});

Плюсы: все обработчики событий документированы в одном месте для модуля. Нет кода, загромождающего каждый обработчик успеха ajax.

Минусы: я не уверен, если таковые имеются.

Пожалуйста, сообщите, если какие-либо предложения.

Ответы на вопрос(3)

Ваш ответ на вопрос