简体   繁体   English

在作为onclick函数的函数中删除事件侦听器/ onclick

[英]Removing event listener / onclick in the function that is the onclick function

I am trying to remove an event listener in a function that is the same function that is called by onclick . 我试图在与onclick调用的函数相同的函数中删除事件侦听器。

The following example illustrates my problem. 以下示例说明了我的问题。 The reason I am trying to use that kind of construction is to pass a function to a view object so that it can add it as an onclick function to created elements. 我尝试使用这种构造的原因是将函数传递给视图对象,以便可以将其作为onclick函数添加到创建的元素中。

"use strict";

// Do I need var fun = function()... here or I could use only function fun() { ....}?
var fun = function(obj, num) {
  alert(obj.id + ' ' + num);
  obj.onclick = ""; // Version 1. This seems to work
  //obj.removeEventListener('click', ); // Version 2. What should I add after the comma to remove EventListener?

}

setFn(fun);

function setFn(fn) {

  var funct = fn;

  var val = 10;
  var elem = document.getElementById('test');
  // The next function works with and without return. What are the differences? Are there any possible memory leaks?
  elem.onclick = function() { funct(this, 11); }; // Version 1. Why in this case 'this' is not referring to the global 'window'?
  //elem.addEventListener('click', function() {funct(this, val); }); // Version 2.
}

Thank you in advance. 先感谢您。

You can't do it that way. 你不能那样做。 You have no reference to the anonymous function you passed to .addEventListener() in version 2, so it can't be removed. 您没有引用在版本2中传递给.addEventListener()的匿名函数,因此无法将其删除。

One possibility would be to name the currently anonymous function, and pass it in to funct as a third argument. 一种可能是命名当前匿名函数,并将其作为第三个参数传递给funct

elem.addEventListener('click', function f() {funct(this, val, f); });

Then fun can use that to remove the listener. 然后fun可以用它来删除侦听。

var fun = function(obj, num, bound_fn) {
  alert(obj.id + ' ' + num);
  if (bound_fn) {
    obj.removeEventListener('click', bound_fn);
  }
}

To remove an event listener you need to pass exactly the same function that was added. 要删除事件监听器,您需要传递与添加的功能完全相同的功能。

"use strict";

var fun = function(obj, num, originalEventHandler) {
  alert(obj.id + ' ' + num);
  obj.removeEventListener('click', originalEventHandler);
}

function setFn(fn) {
  var element = document.getElementById('test');

  element.addEventListener('click', function eventHandler() {
    fn(this, 11, eventHandler);
  });
}

setFn(fun);

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM