There are all sorts of events related to web development--both front and back end events. Developing an organized event system is important because it provides users (and developers) with a level of reliable API interactivity--the most notable of these being the display of information, and keyboard and mouse events. But adding more features requires a finer level of control as web pages get more complex. For example, instead of adding all event listeners to the window object, we might choose to place some of them on individual DOM nodes.
During some experimentation, I ran into this very situation while building a crude drawing app.​​​​​​​
If you open your DevTools and look at “Sources”, you’ll see the app.js file. In it, I add event listeners (and even remove an event listener based on a different event). The finer level of control that I needed here was on the “Clear” button and the color swatches, because I wanted to mitigate drawing on top of them. To gain that control I used the .stopPropagation() method, which allows the user to click on the button and swatches, but prohibits drawing on top of those elements.

Digging deeper into the construct of event systems, a basic decorator function of registering and triggering events might look like this:
const eventSystem = target => { = {};
  target.on = function(event, callback) {[event] =[event] || [];[event].push(callback);
  target.trigger = function(event) {[event].forEach(fn => fn());
Decorate an object like this: eventSystem(object); or even eventSystem(DOMnode);
Register functionality with the .on() method.
Trigger functionality with the .trigger() method.

During some further experimentation, I implemented an event system (shown below) with DOM nodes using the eventSystem object decorator. This system decorates three DOM nodes and is cyclic in that the events trigger each other in a ping-pong loop. Of course, this same functionality can be achieved in different ways; it’s simply an illustration of how an event system might be constructed and used to trigger events.

You may also like

Back to Top