I hate jQuery. Unfortunately, it's used a lot in one of my work's largest projects and I cringe every time I have to deal with it. I'm currently in the long overdue process of upgrading a lot of the JavaScript (and migrating to TypeScript) and there's one piece of jQuery I'm not so sure how to best replace.
The method in question would be jQuery's on(events [, selector] [, data] [, handler ])
method. It allows you to create event listeners for a selector, before any elements matching the selector have been added to the DOM. As far as jQuery methods go, this one isn't bad.
To replace it, my first thought would be to use something like this:
function on(event, selector, handler) {
addEventListener(event, ev => {
if (ev.target.matches(selector)) {
handler()
}
}
}
That doesn't look too efficient in my opinion and I'm unsure if it's the best way to replace the method. Am I correct in my thoughts and if so, what would be the best way to replace the method?