Last active
December 19, 2015 01:19
-
-
Save ngsankha/5875354 to your computer and use it in GitHub Desktop.
Simple event handling mechanism
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
"use strict"; | |
/* EventEmitter - simple event handling | |
* | |
* Use var myObj = Object.create(EventEmitter) to inherit the functions | |
* Use myObj.on('event', callback) to attach event handlers | |
* Use emit('event') to trigger the event handlers | |
*/ | |
var EventEmitter = { | |
handlers: {}, | |
emit: function (event, data) { | |
if (this.handlers.hasOwnProperty(event)) { | |
for (var i = 0; i < this.handlers[event].length; i++) | |
this.handlers[event][i](data); | |
} | |
}, | |
on: function (event, callback) { | |
if (this.handlers.hasOwnProperty(event)) | |
this.handlers[event].push(callback); | |
else | |
this.handlers[event] = [callback]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment