Created
September 13, 2013 01:18
-
-
Save lot224/6545870 to your computer and use it in GitHub Desktop.
Simple Javascript Event Engine.
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
; (function (window, undefined) { | |
window.events = function (name) { | |
if (typeof name !== 'string') | |
return undefined; | |
name = name.toLowerCase(); | |
if (!(window.events.collection[name] instanceof window.events.event)) | |
window.events.collection[name] = new window.events.event(name); | |
return window.events.collection[name]; | |
} | |
window.events.collection = []; | |
window.events.event = function (name) { | |
var _ctrl = this; | |
_ctrl.name = name; | |
_ctrl.subscribers = []; | |
_ctrl.subscribe = function (func) { | |
if (typeof func !== 'function') | |
return null; | |
var key = (function () { | |
var S4 = function () { | |
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); | |
}; | |
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); | |
})(); | |
this.subscribers[key] = func; | |
return key; | |
} | |
_ctrl.raise = function (sender, args) { | |
for (index in _ctrl.subscribers) { | |
if (typeof (_ctrl.subscribers[index]) === 'function') { | |
if (args instanceof Array) { | |
_ctrl.subscribers[index].apply(sender, args); | |
} else { | |
_ctrl.subscribers[index].call(sender, args); | |
} | |
} | |
} | |
}; | |
_ctrl.unsubscribe = function (key) { | |
delete _ctrl.subscribers[key]; | |
} | |
_ctrl.dispose = function () { | |
delete window.events.collection[_ctrl.name] | |
} | |
} | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment