删除匿名事件侦听器

问题描述 投票:42回答:11

无论如何要删除像这样添加的事件监听器:

element.addEventListener(event, function(){/* do work here */}, false);

没有替换元素?

javascript greasemonkey addeventlistener userscripts
11个回答
19
投票

除非在创建时存储对事件处理程序的引用,否则无法干净地删除事件处理程序。

我通常会将这些添加到该页面上的主对象,然后您可以在完成该对象时迭代并干净地处理它们。


0
投票

Jquery .off()方法删除与.on()附加的事件处理程序


0
投票

使用ECMAScript2015(ES2015,ES6)语言规范,可以使用这个nameAndSelfBind函数,它将匿名回调神奇地转换为命名回调,甚至将其身体绑定到自身,允许事件监听器从内部移除自身以及它要从外部范围中移除(JSFiddle):

(function()
{
  // an optional constant to store references to all named and bound functions:
  const arrayOfFormerlyAnonymousFunctions = [],
        removeEventListenerAfterDelay = 3000; // an auxiliary variable for setTimeout

  // this function both names argument function and makes it self-aware,
  // binding it to itself; useful e.g. for event listeners which then will be able
  // self-remove from within an anonymous functions they use as callbacks:
  function nameAndSelfBind(functionToNameAndSelfBind,
                           name = 'namedAndBoundFunction', // optional
                           outerScopeReference)            // optional
  {
    const functionAsObject = {
                                [name]()
                                {
                                  return binder(...arguments);
                                }
                             },
          namedAndBoundFunction = functionAsObject[name];

    // if no arbitrary-naming functionality is required, then the constants above are
    // not needed, and the following function should be just "var namedAndBoundFunction = ":
    var binder = function() 
    { 
      return functionToNameAndSelfBind.bind(namedAndBoundFunction, ...arguments)();
    }

    // this optional functionality allows to assign the function to a outer scope variable
    // if can not be done otherwise; useful for example for the ability to remove event
    // listeners from the outer scope:
    if (typeof outerScopeReference !== 'undefined')
    {
      if (outerScopeReference instanceof Array)
      {
        outerScopeReference.push(namedAndBoundFunction);
      }
      else
      {
        outerScopeReference = namedAndBoundFunction;
      }
    }
    return namedAndBoundFunction;
  }

  // removeEventListener callback can not remove the listener if the callback is an anonymous
  // function, but thanks to the nameAndSelfBind function it is now possible; this listener
  // removes itself right after the first time being triggered:
  document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
  {
    e.target.removeEventListener('visibilitychange', this, false);
    console.log('\nEvent listener 1 triggered:', e, '\nthis: ', this,
                '\n\nremoveEventListener 1 was called; if "this" value was correct, "'
                + e.type + '"" event will not listened to any more');
  }, undefined, arrayOfFormerlyAnonymousFunctions), false);

  // to prove that deanonymized functions -- even when they have the same 'namedAndBoundFunction'
  // name -- belong to different scopes and hence removing one does not mean removing another,
  // a different event listener is added:
  document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
  {
    console.log('\nEvent listener 2 triggered:', e, '\nthis: ', this);
  }, undefined, arrayOfFormerlyAnonymousFunctions), false);

  // to check that arrayOfFormerlyAnonymousFunctions constant does keep a valid reference to
  // formerly anonymous callback function of one of the event listeners, an attempt to remove
  // it is made:
  setTimeout(function(delay)
  {
    document.removeEventListener('visibilitychange',
             arrayOfFormerlyAnonymousFunctions[arrayOfFormerlyAnonymousFunctions.length - 1],
             false);
    console.log('\nAfter ' + delay + 'ms, an event listener 2 was removed;  if reference in '
                + 'arrayOfFormerlyAnonymousFunctions value was correct, the event will not '
                + 'be listened to any more', arrayOfFormerlyAnonymousFunctions);
  }, removeEventListenerAfterDelay, removeEventListenerAfterDelay);
})();

16
投票

你可以像这样删除事件监听器:

element.addEventListener("click", function clicked() {
    element.removeEventListener("click", clicked, false);
}, false);

10
投票

匿名绑定事件侦听器

删除元素的所有事件侦听器的最简单方法是将其outerHTML分配给自身。这样做是通过HTML解析器发送HTML的字符串表示,并将解析后的HTML分配给元素。因为没有传递JavaScript,所以不会有绑定的事件侦听器。

document.getElementById('demo').addEventListener('click', function(){
    alert('Clickrd');
    this.outerHTML = this.outerHTML;
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>

匿名委派的事件侦听器

一个警告是委托事件监听器或父元素上的事件监听器,它监视与其子项上的一组条件匹配的每个事件。过去的唯一方法是将元素更改为不符合委托事件侦听器的条件。

document.body.addEventListener('click', function(e){
    if(e.target.id === 'demo') {
        alert('Clickrd');
        e.target.id = 'omed';
    }
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>

4
投票

您可以尝试覆盖element.addEventListener并做任何你想做的事情。 就像是:

var orig = element.addEventListener;

element.addEventListener = function (type, listener) {
    if (/dontwant/.test(listener.toSource())) { // listener has something i dont want
        // do nothing
    } else {
        orig.apply(this, Array.prototype.slice.apply(arguments));
    }
};

ps。:不推荐,但它会做的伎俩(没有测试过)


3
投票

编辑:正如Manngo建议的每条评论,你应该使用.off()而不是.unbind(),因为.unbind()从jQuery 3.0开始被弃用,并且从jQuery 1.7开始被取代。

即使这是一个老问题而且它没有提到jQuery我会在这里发布我的答案,因为它是searchterm'jquery删除匿名事件处理程序'的第一个结果。

您可以尝试使用.off()函数删除它。

$('#button1').click(function() {
       alert('This is a test');
});

$('#btnRemoveListener').click(function() {
       $('#button1').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Click me</button>
<hr/>
<button id="btnRemoveListener">Remove listener</button>

但是这只有在你使用jQuery添加监听器时才有效 - 而不是.addEventListener

发现这个here


2
投票

使用文字函数分配事件处理程序是棘手的 - 不仅没有办法删除它们,没有克隆节点并用克隆替换它 - 你也可能无意中多次分配相同的处理程序,如果你使用一个对处理程序的引用。两个函数始终被视为两个不同的对象,即使它们的字符相同。


2
投票

旧问题,但这是一个解决方案。

严格来说,除非存储对函数的引用,否则无法删除匿名事件侦听器。由于使用匿名函数的目标可能不是创建新变量,而是可以将引用存储在元素本身中:

element.addEventListener('click',element.fn=function fn() {
    //  Event Code
}, false);

稍后,当您要删除它时,您可以执行以下操作:

element.removeEventListener('click',element.fn, false);

请记住,第三个参数(false)必须与添加事件侦听器的值相同。

然而,这个问题本身就是另一个问题:为什么?

使用.addEventListener()而不是简单的.onsomething()方法有两个原因:

首先,它允许添加多个事件侦听器。当有选择地删除它时,这成为一个问题:你可能最终命名它们。如果你想将它们全部删除,那么@ tidy-giant的outerHTML解决方案非常棒。

其次,您可以选择捕获而不是冒泡事件。

如果两个原因都不重要,您可能决定使用更简单的onsomething方法。


0
投票

以下对我来说效果很好。代码处理另一个事件触发从元素中删除侦听器的情况。事先不需要函数声明。

myElem.addEventListener("click", myFunc = function() { /*do stuff*/ });

/*things happen*/

myElem.removeEventListener("click", myFunc);

0
投票

如果你正在使用jQuery尝试off方法

$("element").off("event");
© www.soinside.com 2019 - 2024. All rights reserved.