diff --git a/lib/off.js b/lib/off.js index 4e33ef3..5dade3d 100644 --- a/lib/off.js +++ b/lib/off.js @@ -4,17 +4,23 @@ function off(selector, event) { if (Array.isArray(selector)) { selector.forEach((item) => off(item, event)); } - if (!window._domassistevents || !window._domassistevents[`_${event}`]) { - return; + if (!window._domassistevents) { + window._domassistevents = {}; } // only disable events that were registered with domassist.on, // don't de-register events that were registered by other libs: const data = window._domassistevents[`_${event}`]; + + if (!data) { + return; + } + const el = find(selector); + if (el.length) { el.forEach((item) => { - item.removeEventListener(event, data.cb, data.capture); + item.removeEventListener(event, data.cb, data.options); }); } } diff --git a/lib/on.js b/lib/on.js index f049545..701b640 100644 --- a/lib/on.js +++ b/lib/on.js @@ -1,25 +1,24 @@ import find from './find'; -function on(selector, event, cb, capture = false) { +function on(selector, event, cb, options) { if (Array.isArray(selector)) { - selector.forEach((item) => on(item, event, cb, capture)); + selector.forEach((item) => on(item, event, cb, options)); return; } - // scrolling events need the passive listener attached - // to satisfy SEO scrolling measurements: - if (['touchstart', 'touchmove', 'wheel', 'mousewheel', 'scroll'].indexOf(event) !== -1) { - if (capture === false) { - capture = { passive: true }; - } - if (capture === true) { - capture = { passive: true, capture: true }; - } - if (typeof capture === 'object') { - capture.passive = true; - } + let eventOptions = {}; + + if (typeof options === 'boolean') { + eventOptions.capture = options; + } else if (typeof options === 'object') { + eventOptions = { ...options }; } + const data = { + cb, + options: eventOptions + }; + // _domassistevents keeps track of events we registered // with 'domassist.on' so they can be deregistered by // 'domassist.off' without affecting events registered @@ -27,15 +26,13 @@ function on(selector, event, cb, capture = false) { if (!window._domassistevents) { window._domassistevents = {}; } - window._domassistevents[`_${event}`] = { - cb, - capture - }; + window._domassistevents[`_${event}`] = data; const el = find(selector); + if (el.length) { el.forEach((item) => { - item.addEventListener(event, cb, capture); + item.addEventListener(event, cb, eventOptions); }); } }