Created
July 4, 2022 03:56
-
-
Save Ragzzy-R/2fcc110f823d5ed9e14c4b080b5cbe97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple Event system similar to | |
* DOM's synthetic events. | |
*/ | |
export class Event { | |
constructor(name) { | |
this.name = name; | |
this.callbacks = []; | |
} | |
registerCallback(callback) { | |
this.callbacks.push(callback); | |
} | |
} | |
export class EventReactor { | |
constructor() { | |
this.events = {}; | |
} | |
registerEvent = function (eventName) { | |
var event = new Event(eventName); | |
this.events[eventName] = event; | |
}; | |
dispatchEvent = function (eventName, eventArgs) { | |
this.events[eventName].callbacks.forEach(function (callback) { | |
callback(eventArgs); | |
}); | |
}; | |
addEventListener = function (eventName, callback) { | |
this.registerEvent(eventName); | |
this.events[eventName].registerCallback(callback); | |
}; | |
} | |
//usage | |
const reactor = new EventReactor(); | |
reactor.addEventListener('foo', (data)=> { console.log('foo fired with', data) }; // prints foo fired with {name: 'ragzzy', id:42} | |
// to emit the event | |
reactor.dispatchEvent('foo', {name: 'ragzzy', id: 42}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment