Skip to content

Instantly share code, notes, and snippets.

@disgusting-dev
Last active September 6, 2023 09:49
Show Gist options
  • Select an option

  • Save disgusting-dev/8d45aebff8a536af1cba39b0fcd203e3 to your computer and use it in GitHub Desktop.

Select an option

Save disgusting-dev/8d45aebff8a536af1cba39b0fcd203e3 to your computer and use it in GitHub Desktop.
/* Define event listeners to work with */
const isTouch =
typeof window !== 'undefined'
&& ('ontouchstart' in window || navigator.msMaxTouchPoints > 0);
const events = isTouch
? ['touchstart', 'click']
: ['click'];
/* End of events definition */
const instances = [];
//1.
function onClickOutside({ event, el, handler }) {
const isClickOutside =
event.target !== el
&& !el.contains(event.target);
return isClickOutside ? handler(event, el) : null;
}
//2.
document.addEventListener('click', (event) => onClickOutside({ event }))
//3.
const instances = [];
//4.
function bind(el, { value: handler }) {
//5.
const instance = {
el,
eventHandlers: eventAdapter(events),
};
//6.
toggleEventListeners(instance);
instances.push(instance);
}
function update(el, { value }) {
//7.
const instance = instances.find(item => item.el === el);
//8.
removeIstanceListeners(instance);
//9.
instance.eventHandlers = eventAdapter(events)
//10.
toggleEventListeners(instance, 'add');
}
function unbind(el) {
const instance = instances.find(item => item.el === el);
toggleEventListeners(instance, 'remove');
}
function processArgs(value) {
}
function toggleEventListeners(instance, action) {
instance.eventHandlers.forEach(({ event, handler }) =>
document[`${action}EventListener`](event, handler),
);
}
function eventAdapter(events) {
return events.map((eventName) => ({
event: eventName,
handler: (event) => onEvent({ event, el, handler, middleware })
}));
}
const directive = {
bind,
update,
unbind,
};
export default directive;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment