|
|
|
|
|
by noduerme
866 days ago
|
|
I was going to post on HN not long ago and didn't, about how I still can't find a great event chain handling / bubbling model that lets me use both DOM members and abstract class instances to trigger interchangeable events. I've built my own event dispatchers here and there, but jQuery just does everything right. Although event handling is almost the only thing I still use jQuery for, it's so useful that I still include it in almost every client-side project. The reason I was going to post was to ask if anyone knew of a slim library that could both $(window).trigger('click') and $(myClassInstance).trigger('myCustomEvent',{data}) with the same API for listening to either one asynchronously. With the rise of fetch() and css selectors I could probably do without the rest of jQuery at this point. But why reinvent the wheel? And before anyone tells me that having class instances dispatch events is a code smell... it's absolutely necessary if you want to build responsive frameworks from scratch. [Just for example, my base component class listens for a particular custom resize event dispatched from the screen that contains it, which only dispatches to components on screens that don't scroll and need to reformat their contents. The screen class listens for window.resize but only dispatches if it's in trouble with the layout. Putting individual DOM resize listeners to window on each and every component would be insane.] |
|
For triggering 'click' events and such, you can create and dispatch native events, as described here [1].
More verbose than jquery, like most native DOM APIs, but works well.
If you're not dealing with a DOM element and just need to dispatch/listen from a class, try out EventTarget [2]?
Your class can inherit from EventTarget, and it gets dispatchEvent and addEventListener, just like a DOM element and you can use any of the above things with it:
[1] https://developer.mozilla.org/en-US/docs/Web/Events/Creating...[2] https://developer.mozilla.org/en-US/docs/Web/API/EventTarget