diff --git a/src/utils/custom-event.js b/src/utils/custom-event.js new file mode 100644 index 0000000..587af72 --- /dev/null +++ b/src/utils/custom-event.js @@ -0,0 +1,38 @@ +const NativeCustomEvent = window.CustomEvent; + +/** + * Check for the usage of native support for CustomEvents which is lacking + * completely on IE. + * @return {boolean} Whether it can be used or not. + */ +function canIuseNativeCustom () { + try { + const p = new NativeCustomEvent('t', { detail: { a: 'b' } }); + return 't' === p.type && 'b' === p.detail.a; + } catch (e) { + } + return false; +} + +/** + * Lousy polyfill for the Custom Event constructor for IE. + * @param {!string} type The type of the event. + * @param {?Object} params Additional information for the event. + * @return {Event} + * @constructor + */ +const IECustomEvent = function CustomEvent(type, params) { + const e = document.createEvent('CustomEvent'); + + if (params) { + e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail); + } else { + e.initCustomEvent(type, false, false, undefined); + } + + return e; +}; + +const WSCustomEvent = canIuseNativeCustom() ? NativeCustomEvent : IECustomEvent; + +export default WSCustomEvent; diff --git a/src/utils/dom.js b/src/utils/dom.js index 9fb5ef4..7a1c6d9 100644 --- a/src/utils/dom.js +++ b/src/utils/dom.js @@ -1,3 +1,6 @@ +import WSCustomEvent from './custom-event'; + + /** * Static class for DOM helper. */ @@ -54,4 +57,16 @@ export default class DOM { static unlockScroll() { document.documentElement.style.overflow = 'auto'; } + + /** + * Fires a custom event on the given target. + * @param {Element} target The target of the event. + * @param {string} eventType The event type. + * @param {Object} eventInfo Optional parameter to provide additional data + * to the event. + */ + static fireEvent(target, eventType, eventInfo = { detail: '' }) { + const event = new WSCustomEvent(eventType, eventInfo); + target.dispatchEvent(event); + } }