-
-
Save kevinfilteau/d489b362194cda1243b0d9e7a519246c to your computer and use it in GitHub Desktop.
Reactor Pattern in JavaScript ES6
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
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(); |
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
// 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