Creating a Simple Event Handler for Javascript

Simple! but Necessary
4 min readJul 18, 2021

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:

const SBNEventHandler = function(){
let listeners = {};
const $on = function(event, func){
if(!listeners[event]){
listeners[event] = [];
}
listeners[event].push(func)
};

// Remove the whole listener array

const $off = function(event=undefined){
if(event === undefined){
listeners = {};
}
// Delete the event listeners

if(listeners[event] !== undefined){
delete listeners[event];
}
};

const $emit = function(event, ...args){
// If the event is registered in listeners

if(listeners[event]){
for(let i in listeners[event]){
listeners[event][i](...args);
}
}
};

return {
$on,
$off,
$emit
}

};

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:

// Testing
function hurt(name){
console.log(name + ' Said: "Ouch, It hurts!"');
}

function injured(name){
console.log(name + ' Must be injured!');
}

var eventHandler = SBNEventHandler();
eventHandler.$on('fall', hurt);

// Must only call hurt
console.log('\nhurt() is called:');
eventHandler.$emit('fall', 'John Doe');
// Add Once Event:
eventHandler.$on('fall', injured);

// Must call both
console.log('\nhurt() and injured() are called:');
eventHandler.$emit('fall', 'John Doe');

eventHandler.$off('fall');
console.log('\nNothing will happen:');
eventHandler.$emit('fall', 'John Doe');

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:

let onceListeners = {};const $once = function(event, callback){
if(!onceListeners[event]){
onceListeners[event] = [];
}

// Push the event
onceListeners[event].push(callback);
};
// $emit():
// ...
if(onceListeners[event]){
for(let i in onceListeners[event]){
onceListeners[event][i](...args);

}
// Delete the event functions
delete onceListeners[event];
// ...
// $off():
// ...
if(event === undefined){
listeners = {};
onceListeners = {};
}
// Delete the event listeners

if(listeners[event] !== undefined){
delete listeners[event];
}
if(onceListeners[event] !== undefined){
delete onceListeners[event];
}
// ...

On the main program:

var eventHandler = SBNEventHandler();
eventHandler.$on('fall', hurt);
// Must only call hurt
console.log('\nhurt() is called:');
eventHandler.$emit('fall', 'John Doe');
// Add Once Event:
eventHandler.$once('fall', injured);

// Must call both
console.log('\nhurt() and injured() are called:');
eventHandler.$emit('fall', 'John Doe');
// Must call hurt() only
console.log('\nOnly hurt() is called (hurt is removed automatically):');
eventHandler.$emit('fall', 'John Doe');

eventHandler.$off('fall');
console.log('\nNothing will happen:');
eventHandler.$emit('fall', 'John Doe');

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.

--

--

Simple! but Necessary
0 Followers

Koding yang kelihatan sepele tapi penting akan dibahas di sini!