Skip to content

Instantly share code, notes, and snippets.

@jdgo-mars
Created March 10, 2019 06:59
Show Gist options
  • Save jdgo-mars/6e29b66181219d17c4b34cdf57f8557c to your computer and use it in GitHub Desktop.
Save jdgo-mars/6e29b66181219d17c4b34cdf57f8557c to your computer and use it in GitHub Desktop.
const t = (function () {
var _listeners = {};
/**
* Compare with a new listener handler
* to make sure we are not adding the same handler
* @param String EventType
* @param Function Callback
* @returns Boolean true if exists false if not
*/
var _existsHandler = function (eventType, cb) {
return _getHandlerIndex(eventType, cb) > -1 ? true : false;
//return Object.values(_listeners).some(ls => ls.some(l => l.cb === cb));
};
/**
* Get index of the handler on a specified eventType
* @param String EventType
* @param Function Callback
* @returns -1 if element does not exist OR > -1 if it does
*/
var _getHandlerIndex = function (eventType, cb) {
return _listeners[eventType].findIndex(function (l, n) { return l.cb === cb; });
};
/**
* addListener
* Allow listeners to subscribe for a specific event type
* @param string eventType
* @param ListenerParams <OPTIONAL> Listener options, ATM only includes priority
* @param function callback
* @returns Listener
*/
var subscribe = function (eventType, params, cb) {
if (params === void 0) { params = { priority: 0 }; }
var newListener = {
eventType: eventType,
cb: cb,
priority: params && params.priority ? params.priority : 0
};
// Event Type does not exist create a new array
if (!_listeners[eventType]) {
_listeners[eventType] = [];
// Check if callback already on the listeners stack
}
else if (_existsHandler(eventType, newListener.cb)) {
// TODO: Show some error to the user
return;
}
var isInserted = _listeners[eventType].some(function (l, i) {
// if newListener priority is higher insert at index
if (newListener.priority > l.priority) {
_listeners[eventType].splice(i, 0, newListener);
return true;
}
});
if (!isInserted) {
_listeners[eventType].push(newListener);
}
return newListener;
};
var unsubscribe = function (eventType, cb) {
// If no listener with the associated event Type exists
if (!_listeners[eventType])
return;
var index = _getHandlerIndex(eventType, cb);
if (index < 0)
return;
_listeners[eventType][index] = null;
};
/**
* publish an event to currently subscribed
* listeners on the eventType
* @param EventType The data to be published
* @param data The data to be published
*/
var publish = function (EventType, data) {
// If no listeners on the current eventType
// no need to do stuff
if (!_listeners[EventType])
return;
_listeners[EventType].forEach(function (l) { return l.cb(data); });
};
return {
subscribe: subscribe,
unsubscribe: unsubscribe,
publish: publish
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment