turbolinks缓存出现问题

turbolinks缓存出现问题

本文介绍了无法取消绑定事件监听器 - turbolinks缓存出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绑定然后将ready事件侦听器解绑定到文档。

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

function readyEventHandler(){
//运行一些代码

$(document).unbind(ready);
}

代码不会产生任何错误并且可以正常工作。但是,我的javascript被缓存并复制了代码,所以如果我回去然后在浏览器中转发页面,我最终会运行这个代码不止一次。发生这种情况时,根本不会调用ready事件侦听器。我是否正确解除了此事件监听器的绑定?我知道缓存问题变得有问题(这是它自己的独立问题)但我只是想绑定ready事件监听器,让它运行代码,然后取消绑定它。

解决方案

不太确定它会有所帮助,但这是我的2美分 - 而不是试图解开 readyEventHandler - 确保如果你运行函数一旦不会运行两次:

  var readyHandlerRun = false; 

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

函数readyEventHandler(){
if(readyHandlerRun){
return;
}
readyHandlerRun = true;
//其余代码...
}

另一个选项刚刚弹出:



  $(document).bind(ready, readyEventHandler); function readyEventHandler(){readyEventHandler = function(){} console.log('ready'); //其余代码......}  
 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>  



更新(由@ jason328提供)



  $(文件).bind(ready,function( ){
readyEventHandler();
readyEventHandler = function(){}
});

优雅,就像魅力一样!


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.

解决方案

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!

这篇关于无法取消绑定事件监听器 - turbolinks缓存出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:47