Last active
December 10, 2015 22:58
-
-
Save mattui/4505763 to your computer and use it in GitHub Desktop.
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(Events) { | |
var _listeners = {}; | |
Events.proxy = function(event, handler) { | |
var proxyHandler = function(context) { | |
Events.removeEventListener(event, proxyHandler); | |
handler(context); | |
}; | |
return proxyHandler; | |
} | |
Events.addEventListener = function(event, handler) { | |
_listeners[event] = _listeners[event] || []; | |
_listeners[event].push(handler); | |
}; | |
Events.addWait = function(condition, event, handler) { | |
if (condition()) { | |
handler(); | |
return; | |
} | |
Events.addEventListener(event, Events.proxy(event, handler)); | |
}; | |
Events.removeEventListener = function(event, handler) { | |
var len = _getListeners(event).length; | |
for (var i = len; i >= 0; i--) { | |
if (_listeners[event][i] === handler) { | |
_listeners[event].splice(i, 1); | |
} | |
} | |
}; | |
Events.dispatchEvent = function(event, context) { | |
if (_listeners.hasOwnProperty(event)) { | |
var listeners = _listeners[event].slice(0); | |
for (var i = 0; i < listeners.length; i++) { | |
listeners[i](context); | |
} | |
} | |
}; | |
_getListeners = function(event) { | |
return _listeners[event] || []; | |
} | |
})(window.Events = window.Events || {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment