Last active
December 24, 2015 11:09
-
-
Save garrows/6788931 to your computer and use it in GitHub Desktop.
Simple proxy and event listener
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
MyObject.prototype.on = function (eventName, callback) { | |
if (this.eventListeners[eventName] == undefined) { | |
this.eventListeners[eventName] = []; | |
} | |
if (typeof callback == "function") { | |
this.eventListeners[eventName].push(callback); | |
} else { | |
throw "can not subscribe with a non function callback"; | |
} | |
} | |
MyObject.prototype.publishEvent = function (eventName, data) { | |
if (this.eventListeners[eventName] != undefined) { | |
for (var i = 0; i < this.eventListeners[eventName].length; i++) { | |
this.eventListeners[eventName][i](data); | |
} | |
} | |
} | |
MyObject.prototype.proxy = function () { | |
var self = this; | |
var proxyArgs = []; | |
//arguments isnt actually an array. | |
for (var i = 0; i < arguments.length; i++) { | |
proxyArgs[i] = arguments[i]; | |
} | |
var functionName = proxyArgs.splice(0, 1)[0]; | |
var func = function() { | |
var funcArgs = []; | |
for (var i = 0; i < arguments.length; i++) { | |
funcArgs[i] = arguments[i]; | |
} | |
var allArgs = proxyArgs.concat(funcArgs); | |
self[functionName].apply(self, allArgs); | |
} | |
return func; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment