Last active
August 29, 2015 14:02
-
-
Save nicolopignatelli/ec8c6fc6882951da8770 to your computer and use it in GitHub Desktop.
Basic javascript event dispatcher
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
/** | |
* Usage: | |
* var callback = function(event) { console.log(event); }; | |
* EventDispatcher.addEventListener('event_type', callback); | |
* EventDispatcher.dispatch('event_type', eventData); | |
* EventDispatcher.removeEventListener('event_type', callback); | |
*/ | |
var EventDispatcher = (function() { | |
var _callbacks = {}; | |
return { | |
addEventListener: function(eventType, callback) { | |
if(!_callbacks.hasOwnProperty(eventType)) { | |
_callbacks[eventType] = []; | |
} | |
_callbacks[eventType].push(callback); | |
}, | |
removeEventListener: function(eventType, callback) { | |
if(!_callbacks.hasOwnProperty(eventType)) { | |
return; | |
} | |
var index = _callbacks[eventType].indexOf(callback); | |
_callbacks[eventType].splice(index, 1); | |
}, | |
dispatch: function(eventType, event) { | |
if(!_callbacks.hasOwnProperty(eventType)) { | |
return; | |
} | |
for(var i in _callbacks[eventType]) { | |
_callbacks[eventType][i](event); | |
} | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment