Last active
January 15, 2022 21:57
-
-
Save mohsen1/5123533 to your computer and use it in GitHub Desktop.
Reactor Pattern in JavaScript
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
function Event(name){ | |
this.name = name; | |
this.callbacks = []; | |
} | |
Event.prototype.registerCallback = function(callback){ | |
this.callbacks.push(callback); | |
} | |
function Reactor(){ | |
this.events = {}; | |
} | |
Reactor.prototype.registerEvent = function(eventName){ | |
var event = new Event(eventName); | |
this.events[eventName] = event; | |
}; | |
Reactor.prototype.dispatchEvent = function(eventName, eventArgs){ | |
this.events[eventName].callbacks.forEach(function(callback){ | |
callback(eventArgs); | |
}); | |
}; | |
Reactor.prototype.addEventListener = function(eventName, callback){ | |
this.events[eventName].registerCallback(callback); | |
}; |
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 | |
var reactor = new Reactor(); | |
reactor.registerEvent('big bang'); | |
reactor.addEventListener('big bang', function(){ | |
console.log('This is big bang listener yo!'); | |
}); | |
reactor.addEventListener('big bang', function(){ | |
console.log('This is another big bang listener yo!'); | |
}); | |
reactor.dispatchEvent('big bang'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment