Last active
March 10, 2023 08:54
-
-
Save jammycakes/764e27e4cda061328e859f2ebd1f0733 to your computer and use it in GitHub Desktop.
A replacement for jQuery.on() with a fluent interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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