Unable to unbind event listener - trouble with turbolinks caching

空扰寡人 提交于 2019-12-04 16:17:58

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!

if you just would like to use an eventhamdler only once, you could use one instead of bind

$(document).one("ready", function() {
   // code to run on document ready just for once
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!