Unable to unbind event listener - trouble with turbolinks caching

会有一股神秘感。 提交于 2020-01-01 17:09:17

问题


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.


回答1:


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!




回答2:


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


来源:https://stackoverflow.com/questions/39649910/unable-to-unbind-event-listener-trouble-with-turbolinks-caching

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