Creating a Simple Event Handler for Javascript

Hi, it’s Simple! but Necessary.

This is the second post in a long time. Yea! This time we are going to take a break from so many complicated event handlers.

Events are very important when performing various operations that require a function to be called continuously when something happens.

The occurrence of something can only be caused by a trigger. For example, when you ride a bicycle, if no one pushes you or knocks you down, then you won’t get any cuts from the fall, or you won’t feel embarrassed when you fall. Because basically, you don’t fall. The stored functions, in this case, are injured(), hurt(), and others.

If you learn javascript, you will encounter event listeners such as when a button is pressed, even a component is successfully loaded (usually preceded by an “on” such as onclick, onload, and others).

In terms of events, there are various triggers that can call all the functions stored in an array.

Why should there be an Event Handler?

Event handlers are useful for holding these functions and calling the actions contained in those functions with parameters passed if there is indeed something triggering. An Event Handler needs to be called by a trigger so that the functions inside to be called.

For example, to differentiate from others, we create a function $on to hold the function when an event occurs, $off to delete the contained function, and $emit to trigger the call of the accommodated function.
So simply, it can be illustrated as follows:

In javascript, functions can be parameterized like any other type, without calling when entering them. So the code for the event handler function simply will be as follows:

In this case, let’s say we create a sick and wound function and pass it as a parameter to the $on event handler. For that, consider the following program code:

When the program is run, the following will appear in the console

Note that $on, $emit and $off are working properly and the two hurt and injured methods have been called with their parameters.

we can create a new function that is $once. Where this will be removed once called. So the program code will be like this:

On the main program:

When calling the once, it will automatically remove.

Note that when all the functions contained in $once are executed by $emit, they will be deleted.

Injured Removed Once Emitted

Thus, simply an event listener is created. The Overall Code will be as follows:

This comes in handy when you need it as an event handler in VueJS, React, and any other libraries for a custom handler.

Note that it’s Simple! but Necessary.

Koding yang kelihatan sepele tapi penting akan dibahas di sini!