Skip to content

Instantly share code, notes, and snippets.

@Ragzzy-R
Created July 4, 2022 03:56
Show Gist options
  • Save Ragzzy-R/2fcc110f823d5ed9e14c4b080b5cbe97 to your computer and use it in GitHub Desktop.
Save Ragzzy-R/2fcc110f823d5ed9e14c4b080b5cbe97 to your computer and use it in GitHub Desktop.
/**
* 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