Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Last active December 12, 2024 09:36
Show Gist options
  • Save akbarjondev/47e4bdbea7b06144fd7ca74e00de36de to your computer and use it in GitHub Desktop.
Save akbarjondev/47e4bdbea7b06144fd7ca74e00de36de to your computer and use it in GitHub Desktop.
Adds Event listeners to HTML elements and safely removes them
export function bind(target, { type, listener, options }) {
target.addEventListener(type, listener, options);
return function unbind() {
target.removeEventListener(type, listener, options);
};
}
@akbarjondev
Copy link
Author

akbarjondev commented Jan 8, 2023

Usage

import { bind } from "./eventBinder.js";
const button = document.getElementById("button");

function handleClick(event) {
  console.log("click");
}

const unbind = bind(button, {
  type: "click",
  listener: handleClick,
  options: { capture: true },
});

unbind();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment