Last active
December 18, 2015 00:39
-
-
Save ZhukV/5698381 to your computer and use it in GitHub Desktop.
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
;(function(){ | |
/** | |
* Event dispatcher system | |
*/ | |
function EventDispatcher() | |
{ | |
var _listeners = {}; | |
/** | |
* Add listener | |
* | |
* @param name | |
* @param callback | |
* @param priority | |
*/ | |
this.addListener = function(name, callback, priority) | |
{ | |
if (typeof name == 'undefined') { | |
throw new Error('Name event must be specified'); | |
} | |
if (typeof callback != 'function') { | |
throw new Error('Callback must be a callable'); | |
} | |
if (typeof priority == 'undefined') { | |
priority = 0; | |
} | |
if (typeof priority != 'number') { | |
throw new Error('Priority must be a number.'); | |
} | |
if (typeof _listeners[name] == 'undefined') { | |
_listeners[name] = []; | |
} | |
_listeners[name].push({ | |
callback: callback, | |
priority: priority | |
}); | |
}; | |
/** | |
* Dispatch | |
* | |
* @param name | |
* @param thisContext | |
* @param vars | |
*/ | |
this.dispatch = function(name, thisContext, vars) | |
{ | |
if (typeof _listeners[name] == 'undefined') { | |
return false; | |
} | |
var length = _listeners[name].length, | |
i = 0; | |
for (i = 0; i < length; i++) { | |
_listeners[name][i].callback.apply(thisContext, vars); | |
} | |
return true; | |
} | |
} | |
window.EventDispatcher = EventDispatcher; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment