Skip to content

Instantly share code, notes, and snippets.

@ali5alkaf5
Last active July 18, 2021 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali5alkaf5/2176b06e1206880097eaf51d4774870b to your computer and use it in GitHub Desktop.
Save ali5alkaf5/2176b06e1206880097eaf51d4774870b to your computer and use it in GitHub Desktop.
Simple! but necessary, Simple JS Event Handler
const SBNEventHandler = function(){
let listeners = {};
let onceListeners = {};
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 = {};
onceListeners = {};
}
// Delete the event listeners
if(listeners[event] !== undefined){
delete listeners[event];
}
if(onceListeners[event] !== undefined){
delete onceListeners[event];
}
};
const $once = function(event, callback){
if(!onceListeners[event]){
onceListeners[event] = [];
}
// Push the event
onceListeners[event].push(callback);
};
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);
}
}
if(onceListeners[event]){
for(let i in onceListeners[event]){
onceListeners[event][i](...args);
}
// Delete the event functions
delete onceListeners[event];
}
};
return {
$on,
$once,
$off,
$emit
}
};
// 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.$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 (injured is removed automatically):');
eventHandler.$emit('fall', 'John Doe');
eventHandler.$off('fall');
console.log('\nNothing will happen:');
eventHandler.$emit('fall', 'John Doe');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment