3 ms·
Terms: * Event - an asynchronous action, possibly but not necessarily the result of human or network interaction * Handler - a function that executes instruct
by austincheney 5y ago
Terms:
* Event - an asynchronous action, possibly but not necessarily the result of human or network interaction
* Handler - a function that executes instructions upon the event
* Listener - an abstraction layer to bind handlers to events using an allocation pool and not assignment. One handler may be provided to multiple listeners and one event may receive multiple listeners
* Callback - A function provided to a handler such that instructions not associated with the event are executed via reference
You can assign a handler directly via a DOM property:
myNode.onclick = myHandler;
In this case there is no listener. There is a node, an event, and a handler only. The handler is implicitly provided an event object as its argument (if not explicitly specified), which in turn provides all the identity necessary for the event and node without further abstraction or external assistance. The node identity is `event.target` and the event identity is `event.type`.
The limitation with handler assignment is that only one handler may be simultaneously assigned. This is bad when your media/analytics team, who has no idea what they are doing, installs a bunch of third party spyware on your business site without permission that wants add a bunch of data tracking to every user interaction.
The benefits of handler assignment are: guaranteed garbage collection bound to the assigned DOM node (and more specifically the actual event if the event is reassigned a different handler), code simplicity (forced), no listeners.
A listener allows association of multiple handlers to a single event and/or reuse of a single handler to multiple listeners.
The problems with listeners is that they wildly complicate code and the respective handlers are difficult to garbage collect. As the given node is removed from the document the best practice is to manually call `removeEventListner` on each listener associated with the DOM node. Garbage collection is difficult for these handlers because there is no clear relationship between them and their corresponding events. The risk of not garbage collecting resources is that the application grows in memory with every event interaction, often unnecessarily duplicating allocations, until the application fails. Performance is also impacted in a logarithmic fashion as the stack size increases. This is called leakage.
Frameworks attempt to solve some of these problems with handler/listener allocation, but they aren't universally successful and it is challenging to measure how unsuccessful they are as it varies by instance.