Hacker News new | ask | show | jobs
by claytongulick 864 days ago
If your class instances are attached to the DOM somehow, you may be looking for CustomEvents?

    document.querySelector('#something').dispatchEvent(
      new CustomEvent('myCustomEvent', {...options})
    );
and

    document.querySelector('#something-else').addEventListener('myCustomEvent', () => {...});
You don't even need CustomEvents if you don't need to carry extra data with the event. You can just do

    new Event('myCustomEvent')
and dispatch it.

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:

    class Test extends EventTarget {
    ...
    }

    let foo = new Test();
    foo.dispatchEvent(...);
[1] https://developer.mozilla.org/en-US/docs/Web/Events/Creating...

[2] https://developer.mozilla.org/en-US/docs/Web/API/EventTarget

1 comments

Thanks. Frequently though, my class instances are not attached to the DOM ...more often they're purely data classes that receive occasional updates and listen for events from one another. And it's unweildy or impossible to have them all inherit EventTarget as a base class. In any case it's overkill: I just need a fairly simple event loop to track instances, listeners and callbacks (on or off the DOM) and work as a switchboard for events, with the caveat that it's also nice to be able to pipe native events through the same switchboard when applicable.