DEV Community

Seonyoung Chloe (she/they)
Seonyoung Chloe (she/they)

Posted on

70 : What is the point of Using Event Handler?

Event handlers

Imagine an interface where the only way to find out whether a key on the keyboard is being pressed is to read the current state of that key.

To be able to react to keypresses, you would have to constantly read the key’s state so that you’d catch it before it’s released again. It would be dangerous to perform other time-intensive computations since you might miss a keypress.

Some primitive machines do handle input like that.
A step up from this would be for the hardware or operating system to notice the keypress and put it in a queue.

A program can then periodically check the queue for new events and react to what it finds there.

Of course, it has to remember to look at the queue, and to do it often, because any time between the key being pressed and the program noticing the event will cause the software to feel unresponsive. This approach is called polling.

Most programmers prefer to avoid it.

A better mechanism is for the system to actively notify our code when an event occurs. Browsers do this by allowing us to register functions as handlers for specific events.

<button>Click me</button>
<p>No handler here.</p>
  let button = document.querySelector("button");
  button.addEventListener("click", () => {
    console.log("Button clicked.");
Enter fullscreen mode Exit fullscreen mode

ELS: Handling Events

Top comments (2)

pengeszikra profile image
Peter Vivo

You right, add / remove EventListener is a root of interaction handling.
Frameworks / libraries hide from us.
My favourite functional js library is callbag, which one is really useful at interaction handling, with stream of function.

import { pipe, fromEvent, forEach, take } from 'callbag-basics';
import { debounce } from 'callbag-debounce';

const button = document.querySelector("button");

// formEvent :: source: addEventListener
// debounce :: operator debounce click speed to 300ms
// take :: operator : after 50 click callbag end and that moment fromEvent final his job with removeEventListener
// forEach :: sink: console.log event

  fromEvent(button, 'click'),   
blanchloe profile image
Seonyoung Chloe (she/they)

Cool to know! Thanks!