Last active
December 21, 2015 05:18
-
-
Save ianpgall/6255697 to your computer and use it in GitHub Desktop.
JavaScript constructor library to listen for and trigger events
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
var Subscriber = (function () { | |
"use strict"; | |
var F, allSubscribers, SubClass, PublicClass, handleOn, slice, ret; | |
F = function () { return undefined; }; | |
allSubscribers = {}; | |
SubClass = function (opts) { | |
var me, events; | |
me = this; | |
events = {}; | |
if (!opts) { | |
throw new Error("Subscriber options required"); | |
} | |
if (!opts.name) { | |
throw new Error("Subscriber name required"); | |
} | |
if (!opts["private"]) { | |
allSubscribers[opts.name] = me; | |
} | |
me.on = function (eventName, func) { | |
handleOn(events, eventName, func); | |
return me; | |
}; | |
me.off = function (eventName, func) { | |
var matchedEvent, i, cur; | |
matchedEvent = events[eventName]; | |
if (matchedEvent) { | |
if (func === undefined) { | |
delete events[eventName]; | |
} else { | |
i = matchedEvent.length; | |
while (i--) { | |
cur = matchedEvent[i]; | |
if (cur === func) { | |
matchedEvent.splice(i, 1); | |
} | |
} | |
} | |
} | |
return me; | |
}; | |
me.trigger = function (eventName) { | |
var matchedEvent, args, i, j, cur; | |
matchedEvent = events[eventName]; | |
if (matchedEvent) { | |
args = slice(arguments, 1); | |
for (i = 0, j = matchedEvent.length; i < j; i++) { | |
cur = matchedEvent[i]; | |
F.apply.call(cur, null, args); | |
} | |
} | |
return me; | |
}; | |
me["public"] = function () { | |
return new PublicClass(events); | |
}; | |
}; | |
PublicClass = function (eventObj) { | |
var pub; | |
pub = this; | |
pub.on = function (eventName, func) { | |
handleOn(eventObj, eventName, func); | |
return pub; | |
}; | |
}; | |
handleOn = function (eventObj, eventName, func) { | |
if (!eventObj[eventName]) { | |
eventObj[eventName] = []; | |
} | |
eventObj[eventName].push(func); | |
}; | |
slice = function (arr, start, howMany) { | |
var stop, newArr, i, j, cur; | |
start = +start || 0; | |
howMany = +howMany || Infinity; | |
stop = Math.min(start + howMany, arr.length); | |
newArr = []; | |
for (i = start, j = stop; i < j; i++) { | |
cur = arr[i]; | |
newArr.push(cur); | |
} | |
return newArr; | |
}; | |
ret = function (groupName) { | |
return allSubscribers[groupName]; | |
}; | |
ret.create = (function () { | |
var Sub = function (args) { | |
return SubClass.apply(this, args); | |
}; | |
Sub.prototype = SubClass.prototype; | |
return function () { | |
return new Sub(arguments); | |
}; | |
}()); | |
return ret; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment