5

Trying to remove the keydown event listener. It says I need to use a named function. Isn't doStuff() a named function? Why doesn't it work? I wan't to remove the keydown event if someone types they E key. So after E the console should not long anymore anything. What am I doing wrong?

(function(){
  'use strict'

  class Blubb {
      constructor() {
          this.init();
      }
      
      init() {
          document.addEventListener('keydown', (function(event) {
              this.doStuff(event);
          }).bind(this));
      }
      
      doStuff(event) {
          if(event.keyCode === 69) {
              console.log('remove event listener', event.keyCode);
              document.removeEventListener('keydown', (function(event) {
                  this.doStuff(event);
              }).bind(this));
          } else {
              console.log('blubb', event.keyCode);
          }
      }
  };
  
  new Blubb();

})();
<h3>Press key on keyboard</h3>
<h3>Press "E" to remove Event Listener</h3>
caramba
  • 21,963
  • 19
  • 86
  • 127
  • Try without bind – Piterden Nov 17 '17 at 14:50
  • 3
    Add `this.doStuff = this.doStuff.bind(this)` in constructor and then use `document.addEventListener('keydown', this.doStuff);` and `document.removeEventListener('keydown', this.doStuff)`. – dfsq Nov 17 '17 at 14:52
  • a named function is when you use something like this addEventListener('event', namedFunction) and removeEventListener('event', namedFunction) – Coldblue Nov 17 '17 at 14:52
  • @dfsq thank you! that solved it! – caramba Nov 17 '17 at 14:59
  • @dfsq, nice try. I really wish this would work, but ... alas! it doesn't. I still get key responses after I press 'E'. This stuff is a big pain! – Apostolos Mar 06 '21 at 11:35
  • Whoever closed this thread saying that "There is already an answer", he/she has to know what he/she is doing. Because 1) the link contains **NO `keydown` events** (which is asked for here) and 2) all the answers include **mouse clicking** !! (In short, the link does not offer an answer to **this** question.) – Apostolos Mar 06 '21 at 11:41
  • @Apostolos is doesn't matter if it is `keydown` or `click` event as they are all `events`. [See dfsq comment above](https://stackoverflow.com/questions/47353322/remove-keydown-event-listener?noredirect=1#comment81658907_47353322) that solves the issue – caramba Mar 07 '21 at 08:10
  • @caramba, OK, maybe so. I wouldn't know. What I know is that the question here is about **keypress** and the link refers to **clicking**, which is **irrelevant**. The main point and issue here is why the `removeEventListener()` as it is set above does not work, which indeed doesn't. So the question is **unanswered** and yet closed! So, whoever closed it, should at least refer to **https://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript**, which **does contain** a solution, and a great one (by member **user8967105**.) – Apostolos Mar 07 '21 at 17:25

0 Answers0