jason328 jason328 - 2 months ago 13
Javascript Question

Unable to unbind event listener - trouble with turbolinks caching

I'm binding then unbinding the ready event listener to the document.

$(document).bind("ready", readyEventHandler);

function readyEventHandler() {
// run some code

$(document).unbind("ready");
}


The code produces no errors and will work. However, my javascript is cached and duplicates the code so I'll end up with having this code run more than once if I go back and then forward a page in the browser. When this happens, the ready event listener is not called at all. Am I properly unbinding this event listener? I know the caching issue becomes problematic(it's own separate issue) but I just want to bind the ready event listener, have it run code, then unbind it.

Answer

Not so sure it will help, but here are my 2 cents - instead of trying to unbind the readyEventHandler - make sure that if you run the function once it will not run twice:

var readyHandlerRun = false;

$(document).bind("ready", readyEventHandler);

function readyEventHandler() {
    if (readyHandlerRun) {
        return;
    }
    readyHandlerRun = true;
    // Rest of your code...
}

Another options that popped just now:

$(document).bind("ready", readyEventHandler);
function readyEventHandler() {
  readyEventHandler = function() { }  
  
  console.log('ready');
  // Rest of your code...
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

UPDATE (by @jason328)

After talking with Dekel he provided me the appropriate answer.

$(document).bind("ready", function() {
    readyEventHandler();
    readyEventHandler = function() { }
});

Elegant and works like a charm!

Comments