Skip to content

Instantly share code, notes, and snippets.

@MAKIO135
Last active January 23, 2021 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MAKIO135/56bab1f268639a0878b4af22c3b52f69 to your computer and use it in GitHub Desktop.
Save MAKIO135/56bab1f268639a0878b4af22c3b52f69 to your computer and use it in GitHub Desktop.
JS Reactor Pattern for creating custom Events
<!DOCTYPE html>
<title>Hello Reactor</title>
<script src="reactor.js"></script>
<script src="main.js"></script>
const reactor = new Reactor()
reactor.on('big bang', () => console.log('This is big bang listener!'))
reactor.on('big bang', (...args) => console.log(args))
reactor.dispatchEvent('big bang', 135, 'test', [1, 2, 3])
class Event {
constructor(name) {
this.name = name
this.callbacks = []
}
registerCallback(callback) {
this.callbacks.push(callback)
}
}
class Reactor {
constructor() {
this.events = {}
}
registerEvent(eventName) {
this.events[eventName] = new Event(eventName)
}
dispatchEvent(eventName, ...eventArgs) {
this.events[eventName].callbacks.forEach(callback => callback(...eventArgs))
}
on(eventName, callback) {
if(!this.events[eventName]) this.registerEvent(eventName)
this.events[eventName].registerCallback(callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment