JavaScript: remove event listener

290,767

Solution 1

You need to use named functions.

Also, the click variable needs to be outside the handler to increment.

var click_count = 0;

function myClick(event) {
    click_count++;
    if(click_count == 50) {
       // to remove
       canvas.removeEventListener('click', myClick);
    }
}

// to add
canvas.addEventListener('click', myClick);

EDIT: You could close around the click_counter variable like this:

var myClick = (function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
})( 0 );

// to add
canvas.addEventListener('click', myClick);

This way you can increment the counter across several elements.


If you don't want that, and want each one to have its own counter, then do this:

var myClick = function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
};

// to add
canvas.addEventListener('click', myClick( 0 ));

EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.

Solution 2

   canvas.addEventListener('click', function(event) {
      click++;
      if(click == 50) {
          this.removeEventListener('click',arguments.callee,false);
      }

Should do it.

Solution 3

You could use a named function expression (in this case the function is named abc), like so:

let click = 0;
canvas.addEventListener('click', function abc(event) {
    click++;
    if (click >= 50) {
        // remove event listener function `abc`
        canvas.removeEventListener('click', abc);
    }
    // More code here ...
}

Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.

More information about named function expressions: http://kangax.github.io/nfe/.

Solution 4

If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.

clickHandler = function(event){
  if (click++ == 49)
    canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);

Solution 5

element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();


HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
    this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};


HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
    for (var i = 0; i < this.myListeners.length; i++) {
        this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
    };
   delete this.myListeners;
};
};
Share:
290,767

Related videos on Youtube

thomas
Author by

thomas

Updated on March 03, 2022

Comments

  • thomas
    thomas about 2 years

    I'm trying to remove an event listener inside of a listener definition:

    canvas.addEventListener('click', function(event) {
        click++;
        if(click == 50) {
            // remove this event listener here!
        }
    // More code here ...
    

    How could I do that? this = event...

    • rlemon
      rlemon about 12 years
      trivial but for the future references if(click == 50) { should be if( click === 50 ) or if( click >= 50 ) - they will not change the output, but for sanity reasons these checks make more sense.
    • JasonXA
      JasonXA almost 9 years
      Good question... how do I remove it if I don't have access to the content? I want to remove popups for onclick on buttons using greasemonkey for other sites, but unless I can reference the function by name, I don't seem to find a way to remove it.
  • Ender
    Ender over 13 years
    This is cool! Doc on arguments.callee for interested parties: developer.mozilla.org/en/JavaScript/Reference/…
  • karim79
    karim79 over 13 years
    +1 - I made this into a fiddle and it did not work. But that was because I needed to click fifty times :) What an idiot I am. Simplified example here: jsfiddle.net/karim79/aZNqA
  • user113716
    user113716 over 13 years
    @karim79: I wish I could say I've never done anything like that before. :o) Thanks for the jsFiddle.
  • Gurnard
    Gurnard over 12 years
    +1 The third option worked for me. Assigning a key event to an input field to clear validation. Nice one thanks
  • SW4
    SW4 almost 9 years
    Upvote, third option here is important part of understanding JS binding/unbinding
  • Daniel Möller
    Daniel Möller almost 9 years
    would myClick = function(event){...} be considered a named function too?
  • Daniel Möller
    Daniel Möller almost 9 years
    I wonder If I could do: myClick = function...., then another = myClick and finally removeEventListener('click', another) ??
  • alebianco
    alebianco over 7 years
    @Daniel since myClick(0) returns a function, of course you can
  • Dai
    Dai almost 4 years
    Unfortunately this doesn't work with ECMAScript 5 (2009) or later, from the MDN link: "The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself." (though it's using callee() instead of callee, it's still removed, boo!)
  • Psuedodoro
    Psuedodoro almost 2 years
    Not really a good practice to help people with however…