@selenite/commons
Version:
This typescript package provides a set of frequently used utilities, types and svelte actions for building projects with Typescript and Svelte.
33 lines (32 loc) • 924 B
JavaScript
/**
* Action to listen to events on the document.
* @param node node the action is bound to
* @param params the listeners and the listeners options combined
* @returns svelte action
*/
export const documentListener = (node, params) => {
function setup() {
Object.keys(params).forEach((key) => {
const p = params;
if (typeof p[key] !== 'function')
return;
document.addEventListener(key, p[key], params);
});
}
setup();
return {
destroy() {
Object.keys(params).forEach((key) => {
const p = params;
if (typeof p[key] !== 'function')
return;
document.removeEventListener(key, p[key], params);
});
},
update(parameter) {
this.destroy?.();
params = parameter;
setup();
}
};
};