Giter VIP home page Giter VIP logo

bind-event-listener's Introduction

bind-event-listener

npm types

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: onClick,
});

// when you are all done:
unbind();
import { bindAll } from 'bind-event-listener';

const unbind = bind(button, [
  {
    type: 'click',
    listener: onClick,
    options: { capture: true },
  },
  {
    type: 'mouseover',
    listener: onMouseOver,
  },
]);

// when you are all done:
unbind();

Rationale

When using addEventListener(), correctly unbinding events with removeEventListener() can be tricky.

  1. You need to remember to call removeEventListener (it can be easy to forget!)
Example
target.addEventListener('click', onClick, options);

// You need to remember to call removeEventListener to unbind the event
target.removeEventListener('click', onClick, options);
  1. You need to pass in the same listener reference to removeEventListener
Example
target.addEventListener(
  'click',
  function onClick() {
    console.log('clicked');
  },
  options,
);

// Even those the functions look the same, they don't have the same reference.
// The original onClick is not unbound!
target.removeEventListener(
  'click',
  function onClick() {
    console.log('clicked');
  },
  options,
);
// Inline arrow functions can never be unbound because you have lost the reference!
target.addEventListener('click', () => console.log('i will never unbind'), options);
target.removeEventListener('click', () => console.log('i will never unbind'), options);
  1. You need to pass in the same capture value option
Example
// add a listener: AddEventListenerOptions format
target.addEventListener('click', onClick, { capture: true });

// not unbound: no capture value
target.removeEventListener('click', onClick);

// not unbound: different capture value
target.removeEventListener('click', onClick, { capture: false });

// successfully unbound: same capture value
target.removeEventListener('click', onClick, { capture: true });
// this would also unbind (different notation)
target.removeEventListener('click', onClick, true /* shorthand for { capture: true } */);
// add a listener: boolean capture format
target.addEventListener('click', onClick, true /* shorthand for { capture: true } */);

// not unbound: no capture value
target.addEventListener('click', onClick);
// not unbound: different capture value
target.addEventListener('click', onClick, false);

// successfully unbound: same capture value
target.addEventListener('click', onClick, true);
// this would also unbind (different notation)
target.addEventListener('click', onClick, { capture: true });

bind-event-listener solves these problems

  1. When you bind an event (or events with bindAll) you get back a simple unbind function
  2. The unbind function ensures the same listener reference is passed to removeEventListener
  3. The unbind function ensures that whatever capture value is used with addEventListener is used with removeEventListener

Usage

bind: basic

import { bind, UnbindFn } from 'bind-event-listener';

const unbind: UnbindFn = bind(button, {
  type: 'click',
  listener: onClick,
});

// when your are all done:
unbind();

bind: with options

import { bind } from 'bind-event-listener';

const unbind = bind(button, {
  type: 'click',
  listener: onClick,
  options: { capture: true, passive: false },
});

// when you are all done:
unbind();

bindAll: basic

import { bindAll } from 'bind-event-listener';

const unbind = bindAll(button, [
  {
    type: 'click',
    listener: onClick,
  },
]);

// when you are all done:
unbind();

bindAll: with options

import { bindAll } from 'bind-event-listener';

const unbind = bindAll(button, [
  {
    type: 'click',
    listener: onClick,
    options: { passive: true },
  },
  // default options that are applied to all bindings
  { capture: false },
]);

// when you are all done:
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 } }

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[],
  // AddEventListenerOptions is a built in TypeScript type
  sharedOptions?: boolean | AddEventListenerOptions,
): UnbindFn;

type Binding = {
  type: string;
  // EventListenerOrEventListenerObject is a built in TypeScript type
  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

bind-event-listener's People

Contributors

alexreardon avatar dependabot[bot] avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.