1

I originally was reading this: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget

But, then I came upon this question here: How to use JavaScript EventTarget?

However, when or why would a developer need to use EventTarget?

I'm still learning. I know the SO community doesn't like duplicate questions, but I feel this isn't since it's asking a different question than the one I cited above (it only discusses how to use it).

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Netside
  • 80
  • 2
  • 9
  • If you have full control over your application, events might be too general of a solution, and a bit memory heavy. But if you don't, they're a great way to give other parts of the application a way to react to things happening. You could for example have an object than implements an EventTarget and emits an event whenever its data gets refreshed and every other piece of code that needs to know about this could be listening to this event. – Sheraff Feb 22 '20 at 00:50
  • The last example on this article talks about this kind of stuff: http://til.florianpellet.com/2019/12/01/Proxy-use-cases/ – Sheraff Feb 22 '20 at 00:54

1 Answers1

1

For the same reason you might use EventEmitter in node.js: you have some custom class/object which you would like to emit events.

Events are useful to allow your object to notify other parts of your code that something interesting has happened, without the object actually knowing anything about the code that uses it.

For example, a link on a page (implemented by the browser as an HTMLAnchorElement object) does not need to know what your code does in response to clicks; you simply register a click event handler (by calling EventTarget#addEventListener('click', …)) and when clicks happen, the browser internally calls EventTarget#dispatchEvent(new Event('click')) and your code handles the event.

Your own custom objects can use this pattern for a wide range of things. Perhaps you'd like to notify things that your object's data has changed -- either as a result of the user doing something or a fetch call returning.

This allows you to build code that is easily composable and testable: the emitter doesn't care who is listening or what that code does, and the consumers don't care about the implementation details of the event getting fired.

josh3736
  • 139,160
  • 33
  • 216
  • 263