DEV Community

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

Posted on

3

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>
<script>
  let button = document.querySelector("button");
  button.addEventListener("click", () => {
    console.log("Button clicked.");
  });
</script>
Enter fullscreen mode Exit fullscreen mode

ELS: Handling Events

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
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

pipe(
  fromEvent(button, 'click'),   
  debounce(300),
  take(50),
  forEach(console.log)
)
Collapse
 
blanchloe profile image
Seonyoung Chloe (she/they)

Cool to know! Thanks!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more