Skip to content

Instantly share code, notes, and snippets.

@kevinfilteau
Forked from mohsen1/reactor.js
Last active April 15, 2019 12:39
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 kevinfilteau/d489b362194cda1243b0d9e7a519246c to your computer and use it in GitHub Desktop.
Save kevinfilteau/d489b362194cda1243b0d9e7a519246c to your computer and use it in GitHub Desktop.
Reactor Pattern in JavaScript ES6
class ReactorEvent {
constructor(name) {
this.name = name;
this.callbacks = [];
}
registerCallback(callback) {
this.callbacks.push(callback);
}
}
class Reactor {
constructor() {
this.events = {};
}
registerEvent(eventName) {
this.events[eventName] = new ReactorEvent(eventName);
}
dispatchEvent(eventName, eventArgs) {
this.events[eventName].callbacks.forEach(function (callback) {
callback(eventArgs);
});
}
addEventListener(eventName, callback) {
this.events[eventName].registerCallback(callback);
}
}
export const reactor = new Reactor();
// Using it
import {reactor} from 'reactor.js'
reactor.registerEvent('inception');
reactor.addEventListener('inception', function(){
console.log('This is the inception listener!');
});
reactor.addEventListener('big bang', function(){
console.log('This is another the inception listener!');
});
reactor.dispatchEvent('inception');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment