Last active
March 30, 2018 20:15
-
-
Save rbrahul/b6cbc590ff41790bcbacb32af4f67110 to your computer and use it in GitHub Desktop.
Pretty Small Custom EventDispatcher
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
var EventDispatcher= function() { | |
this.events = {}; | |
} | |
EventDispatcher.prototype.add = function(name, handler) { | |
if(!(name in this.events)) { | |
this.events[name] = [handler]; | |
} else { | |
this.events[name].push(handler); | |
} | |
} | |
EventDispatcher.prototype.dispatch = function(name,data) { | |
if(!(name in this.events)) { | |
throw new Error('No event declared using the name '+name); | |
} else { | |
this.events[name].forEach(function(handler) { | |
handler.call(null,data); | |
}); | |
} | |
} | |
var event =new EventDispatcher(); | |
event.add('tick',function(data) { | |
console.log("I have triggered by "+ data.name); | |
}); | |
event.add('run',function(data) { | |
console.log("I am running"); | |
}); | |
event.add('fly',function(data) { | |
console.log("I am flying"); | |
}); | |
event.dispatch('tick', {name: 'rahul'}); | |
event.dispatch('fly'); | |
event.dispatch('run'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment