1

I'm going to start with the opposite of my question: why should events emit only to a specific context when your code is supposed to be easy to interact with?

In the JS world, you can emit events such as:

window.dispatchEvent(
    new CustomEvent('eventName', {
        'detail': {
            'someKey': 'someValue'
        }
    })
);

We are emitting events to the window itself, meaning that everyone can subscribe to these events:

(window).on('eventName', () => ...

The value in doing this is that you don't need to re-build the DOM object (in our case, it could be $(window) and you don't have to worry about what has launched said event, because [window] exists everywhere.

What is the practicality of sending an event to a custom element?

myCustomElementInsteadofWindow.dispatchEvent( requires me to know exactly which element the event fires on.

I assume that the only reason for doing this is for separation of concerns ("well, if an event is only needed within a certain window, why make it fire to the window?"), but...is that question practical in a JS world? Be it on window or myCustomElementInsteadofWindow, there's no constraints imposed by the emitter of an event, so, it's not like behavior is different if I subscribe to these 2 emitters.

4

Would you find it easier to work with JavaScript if dom events were sent directly to window instead of to the impacted dom element?

If your event is not linked to a specific dom element (like the window userproximity event), it makes sense to send it to window directly instead of creating an artificial dom element.

Otherwise, if your event is linked to a dom element (let's say a imagechanged event on an image carousel), send it to the element. You can set the bubbles property of the event to true for it to bubble up to window if no event listener prevents its propagation. That way someone interested in the events of a specific dom element (or maybe in the events of all dom elements under a specific dom element) can easily get them it using the browser's built-in mechanisms, instead of listening to window and filtering the events on a specific field (probably different for every library) that contains the dom element.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.