bind-event-listener

A utility to make binding and (especially) unbinding DOM events easier.
I seem to write this again with every new project, so I made it a library
import { bind, UnbindFn } from 'bind-event-listener';
const unbind: UnbindFn = bind(button, {
type: 'click',
listener: function onClick(event) {},
});
unbind();
import { bindAll } from 'bind-event-listener';
const unbind = bindAll(button, [
{
type: 'click',
listener: function onClick(event) {},
options: { capture: true },
},
{
type: 'mouseover',
listener: function onMouseOver(event) {},
},
]);
unbind();
Rationale
When using addEventListener()
, correctly unbinding events with removeEventListener()
can be tricky.
- You need to remember to call
removeEventListener
(it can be easy to forget!)
Example
target.addEventListener('click', onClick, options);
target.removeEventListener('click', onClick, options);
- You need to pass in the same listener reference to
removeEventListener
Example
target.addEventListener(
'click',
function onClick() {
console.log('clicked');
},
options,
);
target.removeEventListener(
'click',
function onClick() {
console.log('clicked');
},
options,
);
target.addEventListener('click', () => console.log('i will never unbind'), options);
target.removeEventListener('click', () => console.log('i will never unbind'), options);
- You need to pass in the same
capture
value option
Example
target.addEventListener('click', onClick, { capture: true });
target.removeEventListener('click', onClick);
target.removeEventListener('click', onClick, { capture: false });
target.removeEventListener('click', onClick, { capture: true });
target.removeEventListener('click', onClick, true );
target.addEventListener('click', onClick, true );
target.addEventListener('click', onClick);
target.addEventListener('click', onClick, false);
target.addEventListener('click', onClick, true);
target.addEventListener('click', onClick, { capture: true });
bind-event-listener
solves these problems
- When you bind an event (or events with
bindAll
) you get back a simple unbind
function - The unbind function ensures the same listener reference is passed to
removeEventListener
- The unbind function ensures that whatever
capture
value is used with addEventListener
is used with removeEventListener
You will find an even fuller rationale for this project in my course: "The Ultimate Guide for Understanding DOM Events"

Usage
bind
: basic
import { bind, UnbindFn } from 'bind-event-listener';
const unbind: UnbindFn = bind(button, {
type: 'click',
listener: onClick,
});
unbind();
bind
: with options
import { bind } from 'bind-event-listener';
const unbind = bind(button, {
type: 'click',
listener: onClick,
options: { capture: true, passive: false },
});
unbind();
bindAll
: basic
import { bindAll } from 'bind-event-listener';
const unbind = bindAll(button, [
{
type: 'click',
listener: onClick,
},
]);
unbind();
bindAll
: with options
import { bindAll } from 'bind-event-listener';
const unbind = bindAll(button, [
{
type: 'click',
listener: onClick,
options: { passive: true },
},
{ capture: false },
]);
unbind();
When using defaultOptions
for bindAll
, the defaultOptions
are merged with the options
on each binding. Options on the individual bindings will take precedent. You can think of it like this:
const merged: AddEventListenerOptions = {
...defaultOptions,
...options,
};
Note: it is a little bit more complicated than just object spreading as the library will also behave correctly when passing in a boolean
capture argument. An options value can be a boolean { options: true }
which is shorthand for { options: {capture: true } }
Types
Thanks to the great work by @Ayub-Begimkulov bind-event-listener
has fantastic typescript types
import invariant from 'tiny-invariant';
import { bind } from 'bind-event-listener';
bind(window, {
type: 'click',
function: function onClick(event) {
},
});
const button = document.querySelector('button');
invariant(button instanceof HTMLElement);
bind(button, {
type: 'click',
function: function onClick(event) {
},
});
const object = {
handleEvent: function onClick(event) {
},
};
bind(button, {
type: 'click',
function: object,
});
Recipe: react
effect
You can return a cleanup function from useEffect
(or useLayoutEffect
). bind-event-listener
makes this super convenient because you can just return the unbind function from your effect.
import React, { useState, useEffect } from 'react';
import { bind } from 'bind-event-listener';
export default function App() {
const [clickCount, onClick] = useState(0);
useEffect(() => {
const unbind = bind(window, {
type: 'click',
listener: () => onClick((value) => value + 1),
});
return unbind;
}, []);
return <div>Window clicks: {clickCount}</div>;
}
You can play with this example on codesandbox
Types
function bind(target: EventTarget, binding: Binding): UnbindFn;
function bindAll(
target: EventTarget,
bindings: Binding[],
sharedOptions?: boolean | AddEventListenerOptions,
): UnbindFn;
type Binding = {
type: string;
listener: EventListenerOrEventListenerObject;
options?: boolean | AddEventListenerOptions;
};
type UnbindFn = () => void;
Typescript built in DOM types: raw view, pretty view (warning: pretty view seems to crash Github!)
Cheers 👋
Brought to you by @alexandereardon