Skip to content

Instantly share code, notes, and snippets.

@ivan-marquez
Forked from mohsen1/reactor.js
Created October 22, 2018 14:56
Show Gist options
  • Save ivan-marquez/c3778ecaf7ce60108dca2546236b9d3d to your computer and use it in GitHub Desktop.
Save ivan-marquez/c3778ecaf7ce60108dca2546236b9d3d 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