如何销毁“ Popstate”事件侦听器?

Har*_*mpi 2 javascript popstate removeeventlistener

尝试过下面的代码,但它没有破坏Popstate Event

请帮助我们举例说明我可以Popstate Event根据条件销毁。

history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event) {
  if (true){
    history.pushState(null, document.title, location.href);
    console.log('Back Button Prevented');
  } else {
      window.removeEventListener('popstate', ()=> {
          console.log('Go back');
      }, true);
      history.back();
  }
});
Run Code Online (Sandbox Code Playgroud)

Con*_*roß 6

为了删除监听器,您必须将监听器函数本身传递给removeEventListener().

代码中的另一个问题是,使用if (true),您将永远无法到达else正在删除侦听器的块。您可能想要做的是在侦听器之外有一个布尔变量,您可以在第一次调用侦听器时更改该变量。

var backButtonPrevented = false;
history.pushState(null, document.title, location.href);

function popStateListener(event) {
  if (backButtonPrevented === false){
    history.pushState(null, document.title, location.href);
    console.log('Back Button Prevented');
    backButtonPrevented = true;
  } else {
      window.removeEventListener('popstate', popStateListener);
      history.back();
  }
}

window.addEventListener('popstate', popStateListener);
Run Code Online (Sandbox Code Playgroud)