Last active
January 23, 2021 14:59
-
-
Save MAKIO135/56bab1f268639a0878b4af22c3b52f69 to your computer and use it in GitHub Desktop.
JS Reactor Pattern for creating custom Events
This file contains hidden or 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
<!DOCTYPE html> | |
<title>Hello Reactor</title> | |
<script src="reactor.js"></script> | |
<script src="main.js"></script> |
This file contains hidden or 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
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]) |
This file contains hidden or 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 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