Skip to content

Instantly share code, notes, and snippets.

@garrows
Last active December 24, 2015 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garrows/6788931 to your computer and use it in GitHub Desktop.
Save garrows/6788931 to your computer and use it in GitHub Desktop.
Simple proxy and event listener
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