Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* eslint-env browser */
- const subscribtions = {};
- const listeners = {};
- function subscribe(type) {
- const subscribers = [];
- subscribtions[type] = subscribers;
- const listener = event => {
- for (let i = 0; i < subscribers.length; i++) {
- subscribers[i](event);
- }
- };
- listeners[type] = listener;
- window.addEventListener(type, listener);
- }
- function addEventListener(type, cb) {
- if (!type || typeof type !== 'string') {
- throw new Error('addEventListener type parameter must be non empty string.');
- }
- if (typeof cb !== 'function') {
- throw new Error('addEventListener listener parameter must be a function.');
- }
- if (!subscribtions.hasOwnProperty(type) || !Array.isArray(subscribtions[type])) {
- subscribe(type);
- }
- subscribtions[type].push(cb);
- }
- function removeEventListener(type, listener) {
- if (!type || typeof type !== 'string') {
- throw new Error('removeEventListener type parameter must be non empty string.');
- }
- if (typeof cb !== 'function') {
- throw new Error('removeEventListener listener parameter must be a function.');
- }
- if (subscribtions.hasOwnProperty(type)) {
- const subscribers = subscribtions[type];
- const index = subscribers.findIndex(x => x === listener);
- subscribers.splice(index, 1);
- if (subscribers.length === 0) {
- window.removeEventListener(type, listeners[type]);
- delete subscribtions[type];
- delete listeners[type];
- }
- }
- }
- export default { addEventListener, removeEventListener };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement