Created
June 5, 2012 10:15
-
-
Save FireyFly/2874185 to your computer and use it in GitHub Desktop.
Really simple node-like event emitter
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
| // Definition | |
| function EventEmitter() { | |
| var handlers = {} | |
| this.on = function (event, cb) { | |
| if (!handlers[event]) { | |
| handlers[event] = [] | |
| } | |
| handlers[event].push(cb) | |
| } | |
| this.emit = function (event) { | |
| if (!handlers[event]) { return } | |
| var args = Array.prototype.slice.call(arguments, 1) | |
| , self = this | |
| handles[event].forEach(function(handler) { | |
| handler.apply(self, args) | |
| }) | |
| } | |
| } | |
| // Usage | |
| var foo = new EventEmitter() | |
| foo.on('hello', function(arg) { | |
| console.log("foo: hello: %s", arg) | |
| }) | |
| foo.emit('hello', "world!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment