using jQuery's delegated event on() within every turbolinks page:load

蓝咒 提交于 2020-01-02 21:54:34

问题


I had this code in my rails app:

$(document).ready( function() {
  myCustomFunction("#link-selector");
}

function myCustomFunction(linkCssSelector){
  // some stuff...

  $(document).on('click', linkCssSelector, function(){ 
    // ...some other stuff...
  });
}

The click event handling is already delegated to the document, but now I have to add Turbolinks to my app.

Then, I would take of the ready() function and do the following (based on my searches):

$(document).on("ready page:load", function() {
  myCustomFunction("#link-selector");
}

But some references tell me not to add bindings inside the page load, for it would create another binding for each time turbolinks loads something. That's pretty reasonable. But, in my case, I'm already delegating the click event to document inside myCustomFuntion.

The question is: can I run this event delegation on() function every time the page loads without problems?

Obs: Question could also be rephrased: Will this code cause trouble in the long run, after many page loads?

Obs2: I can't take the click event handling from inside myCustomFunction, because it depends on the calculations done before.


回答1:


Adding event handlers to the document on document page:load will as you have read create duplicate handlers. Try running the snipped below:

(click Trigger page:load several times before Click me!)

$(document).on('page:load', function(){
    $(document).on('click', '#test', function(){
      $("#log").append('<li>clicked!</li>');
    });
});
$("#page_load").on('click', function(){
  $(document).trigger('page:load');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="page_load">Trigger page:load</button>
<button id="test">Click me!</button>
<ul id="log"></ul>

Turbolinks basically works by loading pages via Ajax instead and replacing the document contents.

It does try to clean up event handlers when it removes the old page from the DOM - but since your handler is bound to the document it is not removed.

You can relatively safely apply handlers to DOM elements such as the body instead since turbolinks guts out the document and replaces the contents.



来源:https://stackoverflow.com/questions/30405747/using-jquerys-delegated-event-on-within-every-turbolinks-pageload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!