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?
on
depends on thethis
object (the jQuery object on whichon
is called). I don't see this covered in your attempt.this
could be used within the handler. I'm not trying to replicate jQuery, but find the best way to replace it without impacting too much.addEventListener
should be called on the target element, not (necessarily) on thewindow
object. You would need to translate whatever is selected as jQuery object to an equivalent implementation (an argument? Or are you going to usecall(thisArg, ...)
?handler.bind(ev.target, ev)
more than likely. Bind it to the target and pass through the event.on
from jQuery. It uses other jQuery stuff, so it can't be adopted directly, but it might be useful to get an idea of how it woks.