UNPKG

@textback/notification-widget

Version:

TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project.

47 lines (38 loc) 1.25 kB
import assign from 'lodash/assign'; const EVENTS = { WIDGET_INIT: 'widget.init', SUBSCRIBE_START: 'subscribe.start', }; const _handlers = {}; window.TextBack = window.TextBack || {}; window.TextBack.Observer = window.TextBack.Observer || { on(eventName, fn) { if (!_handlers[eventName]) { _handlers[eventName] = [ fn ]; } else { _handlers[eventName].push(fn); } return () => { const fnIndex = _handlers[eventName].indexOf(fn); if (fnIndex !== -1) { _handlers[eventName].splice(fnIndex, 1); } }; }, trigger(eventName, data) { if (_handlers[eventName]) { const eventData = assign({}, data, { type: eventName }); setTimeout(() => { _handlers[eventName].forEach(handler => { try { handler(eventData) } catch (err) { console.error(`Error occuired while executing event handler on event ${eventName}`, err); } }); }, 0); } } }; const Observer = window.TextBack.Observer; export { Observer, EVENTS };