简体   繁体   中英

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 .

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.

"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.

One possibility would be to name the currently anonymous function, and pass it in to funct as a third argument.

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

Then fun can use that to remove the listener.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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