Skip to content

Instantly share code, notes, and snippets.

@jammycakes
Last active March 10, 2023 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jammycakes/764e27e4cda061328e859f2ebd1f0733 to your computer and use it in GitHub Desktop.
Save jammycakes/764e27e4cda061328e859f2ebd1f0733 to your computer and use it in GitHub Desktop.
A replacement for jQuery.on() with a fluent interface
// Usage: bind(event).to(element).for(selector).as(handler)
// e.g. bind("click").to(document.documentElement).for("a").as(e => console.log(e.target.href));
function bind(event) {
return {
to: function(element) {
element = isString(element) ? document.getElementById(element) : element;
return {
as: function(handler) {
element.addEventListener(event, handler);
},
for: function(selector) {
return {
as: function(handler) {
element.addEventListener(event, function(e) {
var t = e.target;
while (t && t !== this) {
if (t.matches(selector)) {
handler.call(t, e);
}
t = t.parentNode;
}
});
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment