删除匿名活动听众

发布于 2025-01-23 02:15:25 字数 139 浏览 0 评论 0 原文

无论如何,是否有添加这样的事件侦听器:

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

不替换元素?

Is there anyway to remove an event listener added like this:

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

Without replacing the element?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

天赋异禀 2025-01-30 02:15:25

除非您在Creation中存储了对事件处理程序的引用,否则无法干净地删除事件处理程序。

我通常会将它们添加到该页面上的主要对象中,然后您可以在使用该对象时迭代并清洁处理它们。

There is no way to cleanly remove an event handler unless you stored a reference to the event handler at creation.

I will generally add these to the main object on that page, then you can iterate and cleanly dispose of them when done with that object.

桃酥萝莉 2025-01-30 02:15:25

您可以这样删除活动听众:

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

You could remove the event listener like this:

element.addEventListener("click", function clicked() {
    element.removeEventListener("click", clicked, false);
}, false);
楠木可依 2025-01-30 02:15:25

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

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

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

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

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

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

但是,问题本身乞求另一个:为什么?

使用 .addeventListener()而不是简单的 .onmetthing()方法:

首先,它允许多>多个事件侦听器是额外。当涉及到选择性地删除它们时,这将成为一个问题:您可能最终会命名它们。如果您想全部删除它们,则 @Tidy-Giant的 OuterHtml 解决方案非常好。

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

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

Old Question, but here is a solution.

Strictly speaking you can’t remove an anonymous event listener unless you store a reference to the function. Since the goal of using an anonymous function is presumably not to create a new variable, you could instead store the reference in the element itself:

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

Later, when you want to remove it, you can do the following:

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

Remember, the third parameter (false) must have the same value as for adding the Event Listener.

However, the question itself begs another: why?

There are two reasons to use .addEventListener() rather than the simpler .onsomething() method:

First, it allows multiple event listeners to be added. This becomes a problem when it comes to removing them selectively: you will probably end up naming them. If you want to remove them all, then @tidy-giant’s outerHTML solution is excellent.

Second, you do have the option of choosing to capture rather than bubble the event.

If neither reason is important, you may well decide to use the simpler onsomething method.

爱她像谁 2025-01-30 02:15:25

匿名 bount 事件侦听器

删除所有事件侦听器的最简单方法是将其 exturalhtml 分配给本身。这样做的是通过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>

Anonymous bound event listeners

The easiest way to remove all event listeners for an element is to assign its outerHTML to itself. What this does is send a string representation of the HTML through the HTML parser and assign the parsed HTML to the element. Because no JavaScript is passed, there will be no bound event listeners.

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


Anonymous delegated event listeners

The one caveat is delegated event listeners, or event listeners on a parent element that watch for every event matching a set of criteria on its children. The only way to get past that is to alter the element to not meet the criteria of the delegated event listener.

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>

南烟 2025-01-30 02:15:25

是的,您可以删除一个匿名事件侦听器:

const controller = new AbortController();

document.addEventListener(
  "click",
  () => {
    // do function stuff
  },
  { signal: controller.signal }
);

然后,您以这样的方式删除事件侦听器:

controller.abort();

Yes you can remove an anonymous event listener:

const controller = new AbortController();

document.addEventListener(
  "click",
  () => {
    // do function stuff
  },
  { signal: controller.signal }
);

You then remove the event listener like this:

controller.abort();
予囚 2025-01-30 02:15:25

您可以尝试覆盖 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。:不建议这样做,但它会做到这一点(尚未对其进行测试)

You may try to overwrite element.addEventListener and do whatever you want.
Something like:

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.: it is not recommended, but it will do the trick (haven't tested it)

终弃我 2025-01-30 02:15:25

用字面函数分配事件处理程序很棘手 - 不仅没有任何方法可以删除它们,而不会克隆节点并用克隆替换它 - 您也可以多次无意中分配同一处理程序,如果您使用使用引用处理程序。即使角色相同,两个函数也总是被视为两个不同的对象。

Assigning event handlers with literal functions is tricky- not only is there no way to remove them, without cloning the node and replacing it with the clone- you also can inadvertantly assign the same handler multiple times, which can't happen if you use a reference to a handler. Two functions are always treated as two different objects, even if they are character identical.

来日方长 2025-01-30 02:15:25

编辑: as manngo 建议每个评论,您应该使用 .off()< /strong>而不是 .unbind() as .unbind()被弃用为jQuery 3.0,自JQuery 1.7以来就取代了。

即使这是一个古老的问题,也没有提及jQuery,我也会在这里发布答案,因为这是搜索术语'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添加了侦听器时,这才有效-NOT 。addeventListener

找到此

Edit: As Manngo suggested per comment, you should use .off() instead of .unbind() as .unbind() is deprecated as of jQuery 3.0 and superseded since jQuery 1.7.

Even though this an old question and it does not mention jQuery I will post my answer here as it is the first result for the searchterm 'jquery remove anonymous event handler'.

You could try removing it using the .off() function.

$('#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>

However this only works if you've added the listener using jQuery - not .addEventListener

Found this here.

嘿咻 2025-01-30 02:15:25

如果您使用的是jQuery尝试 off 方法

$("element").off("event");

If you're using jQuery try off method

$("element").off("event");
暮色兮凉城 2025-01-30 02:15:25

jQuery .off()方法删除了随附.on()附加的事件处理程序

Jquery .off() method removes event handlers that were attached with .on()

回眸一遍 2025-01-30 02:15:25

使用Ecmascript2015(ES2015,ES6)语言规范,可以使用此 nameandselfbind 函数,它神奇地将匿名回调变成一个指定的回调,甚至可以将其身体绑定到本身,从而使事件听众可以删除删除本身也可以从外部范围中删除(

(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);
})();

With ECMAScript2015 (ES2015, ES6) language specification, it is possible to do with this nameAndSelfBind function that magically turns an anonymous callback into a named one and even binds its body to itself, allowing the event listener to remove itself from within as well as it to be removed from an outer scope (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);
})();
情何以堪。 2025-01-30 02:15:25
//get Event
let obj = window; //for example
let eventStr= "blur"; //for example
let index= 0; //you can console.log(getEventListeners(obj)[eventStr]) and check index
let e = getEventListeners(obj)[eventStr][index];
//remove this event
obj .removeEventListener(eventStr,e.listener,e.useCapture);

结尾:)
我在Chrome 92中测试,工作

编辑:仅在Chrome中工作,

因为 getEventListeners Chrome中可用的功能。

//get Event
let obj = window; //for example
let eventStr= "blur"; //for example
let index= 0; //you can console.log(getEventListeners(obj)[eventStr]) and check index
let e = getEventListeners(obj)[eventStr][index];
//remove this event
obj .removeEventListener(eventStr,e.listener,e.useCapture);

THE END :)
i test in chrome 92, worked

Edit: Work Only in Chrome

because getEventListeners function available in Chrome.

写给空气的情书 2025-01-30 02:15:25

我如何为我的CustomeVent使用选项参数

options Optional
An object that specifies characteristics about the event listener. The available options are:
...
**once**
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

作为我创建的自定义功能,它效果很好。

const addItemOpenEventListener = (item, openItem) => {
  document.addEventListener('order:open', ({detail}) => {
    if(detail.id === item.id) {
      openItem();
    }
  }, {once: true})
};

el.addItemOpenEventListener(item, () => dispatch(itemOpen)()));

检查了我的控制台,似乎有效(任何反馈都赞赏!)

How I used options parameter for my customEvent

options Optional
An object that specifies characteristics about the event listener. The available options are:
...
**once**
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

for my custom function that I created, it worked quite nicely.

const addItemOpenEventListener = (item, openItem) => {
  document.addEventListener('order:open', ({detail}) => {
    if(detail.id === item.id) {
      openItem();
    }
  }, {once: true})
};

el.addItemOpenEventListener(item, () => dispatch(itemOpen)()));

checked my console, seems like it worked (any feedback appreciated!)

北方。的韩爷 2025-01-30 02:15:25

outerText 答案确实做得很好,但是的问题也将从所有子节点中删除听众。为了解决这个问题,您应该先存储对节点的引用,清除元素,然后在替换 offerText 属性后将其添加回。

以下将从身体元素中删除所有事件听众。

var nodes = [];
document.body.childNodes.forEach((node) => nodes.push(node));
document.body.innerHTML = "";
document.body.outerHTML = document.body.outerHTML;
nodes.forEach((node) => document.body.appendChild(node));

The outerText answer does this really well but has the issue that it will also remove the listeners from all child nodes too. To get around this, you should store a reference to the nodes first, clear the element, then add them back after you've replaced the outerText property.

The following will remove all event listeners from the body element.

var nodes = [];
document.body.childNodes.forEach((node) => nodes.push(node));
document.body.innerHTML = "";
document.body.outerHTML = document.body.outerHTML;
nodes.forEach((node) => document.body.appendChild(node));
眼趣 2025-01-30 02:15:25

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

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

/*things happen*/

myElem.removeEventListener("click", myFunc);

The following worked well enough for me. The code handles the case where another event triggers the listener's removal from the element. No need for function declarations beforehand.

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

/*things happen*/

myElem.removeEventListener("click", myFunc);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文