Pages

Tuesday, 4 November 2014

Removing an Event Listener when using Bind

Problem


If you want to keep the scope of your object in an event listener, you would use 'bind()' as the example below:

document.body.addEventListener('click',this.onBodyClick.bind(this));

The only problem with this is, when you want to remove the listener it doesn't recognise the function.
So this won't work:

document.body.removeEventListener('click',this.onBodyClick.bind(this));

Solution


Because 'bind()' creates a state of that function every time you call it, we need to store that state and use it to remove the listener.

1. Create the bind and store it as a handler variable:

var onBodyClickHandler= this.onBodyClick.bind(this);

2. Then add your listener with the handler variable:

document.body.addEventListener('click',onBodyClickHandler);

3. Now when you remove the listener use the handler variable:

document.body.removeEventListener('click',onBodyClickHandler);

No comments:

Post a Comment