简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM