Skip to content

Instantly share code, notes, and snippets.

@mohsen1
Last active January 15, 2022 21:57
Show Gist options
  • Save mohsen1/5123533 to your computer and use it in GitHub Desktop.
Save mohsen1/5123533 to your computer and use it in GitHub Desktop.
Reactor Pattern in JavaScript
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);
};
// 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