0

我注意到在禁用引导加载项后,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
},
4

1 回答 1

3

因为它是bind'ed。你要做的是:

添加时:

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

于 2014-06-28T20:36:56.663 回答