1

I know there are lots of similar questions out there but somehow I did not find anything for this problem - can you point me in the right direction

Let's say we have a function

window.logMeThis = function(msg){
    console.log(msg);
}

then I need to add an event listener

window.addEventListener('keypress', window.logMeThis.bind(null, "something"));

which looks good at first - but .bind creates a new fn

and now I can't remove the listener

window.removeEventListener('keypress', window.logMeThis);
pszaba
  • 1,034
  • 9
  • 16
  • there is no other magic way. you either store reference to new 'bound' version or you are unable to detach listener. – skyboyer Jun 12 '18 at 11:40
  • Possible duplicate of [Removing event listener which was added with bind](https://stackoverflow.com/questions/11565471/removing-event-listener-which-was-added-with-bind) – Teemu Jun 12 '18 at 11:48
  • @Teemu yes, this question is the one, thanks guys – pszaba Jun 12 '18 at 11:51
  • Just out of curiosity, why to bind an event listener to `null`? If `this` is used in the handler, that would fire an error. Or is that only a simplified example? – Teemu Jun 12 '18 at 12:02
  • 1
    absolutely simplified version, and this was copy pasted – pszaba Jun 12 '18 at 12:05
  • @skyboyer that's not strictly true if you use the `once` option since then the listener is removed once invoked – CervEd Dec 06 '21 at 08:36
  • @CervEd right, but in this case you would nether need to remove event listener manually. – skyboyer Dec 06 '21 at 13:57

3 Answers3

3

You can do that:

window.logMeThis = function(msg){
    console.log(msg);
}
var myFunc = window.logMeThis.bind(null, "something");
window.addEventListener('keypress', myFunc);

To remove the listener, just do that:

window.removeEventListener('keypress', myFunc);

Basically, you need to have a reference of your function to remove it.

Matheus Pitz
  • 456
  • 2
  • 9
0

If you have to bind the function to a specific context then you can do this:

var boundFunction = window.logMeThis.bind(null, "something");
window.addEventListener('keypress', boundFunction);

Now you have a reference to the function to remove it.

Ares
  • 1,356
  • 1
  • 9
  • 22
0

You're right:

This method creates a function whose body is similar to the function on which it is called

just pass the existing function instead and you will be able to reference it like so:

var i = 0;
    window.logMeThis = function(msg){
        console.log(msg+''+i);

      i++;
    }
    window.addEventListener('keypress', window.logMeThis, false);
    window.removeEventListener('keypress', window.logMeThis, false);
Jack
  • 1
  • 2