我已经注意到,在禁用引导加载项之后,removeEventListener似乎并没有删除侦听器,我无法弄清原因。

let contextMenu = window.document.getElementById('contentAreaContextMenu');
if (contextMenu) {
  contextMenu.addEventListener('popupshowing',
            this.contextPopupShowing.bind(this), false);
  // added this to make sure they refer to the same function
  console.log(this.contextPopupShowing.toString());
}


然后禁用插件

console.log(this.contextPopupShowing.toString()); // same as above
this.contextMenu.removeEventListener('popupshowing',
            this.contextPopupShowing.bind(this), false);
// just showing that 'this' is working
this.contextMenu.removeChild(this.menuitem);


终于...

contextPopupShowing: function() {
  // logs even after removeEventListener
  console.log('contextPopupShowing called');
  // more code
},

最佳答案

因为它是bind版本。您要做的是:

添加时:

let contextMenu = window.document.getElementById('contentAreaContextMenu');
if (contextMenu) {
  this.contextPopupShowingBound = this.contextPopupShowing.bind(this);
  contextMenu.addEventListener('popupshowing',
            this.contextPopupShowingBinded, false);
  // added this to make sure they refer to the same function
  console.log(this.contextPopupShowing.toString());
}


然后禁用插件

console.log(this.contextPopupShowing.toString()); // same as above
this.contextMenu.removeEventListener('popupshowing',
            this.contextPopupShowingBound, false);
// just showing that 'this' is working
this.contextMenu.removeChild(this.menuitem);


终于...

contextPopupShowing: function() {
  // logs even after removeEventListener
  console.log('contextPopupShowing called');
  // more code
},


我敢肯定,您不能在bind中使用removeEventListener

请参阅以下主题的出色主题:Removing event listener which was added with bind

07-24 19:12
查看更多