Sha256: cdcf6c01a993ef99293337781e9a81ae1b47f0f8d69c85ebe12a4261a0625102
Contents?: true
Size: 1.88 KB
Versions: 16
Compression:
Stored size: 1.88 KB
Contents
import { kebabCase, camelCase } from "lodash"; export default function withOptions(props = {}) { return function (component) { if (!component.options) { return component; } const el = component.$root; const oldDestroy = component.destroy; const optionsProps = component.options || {}; const optionsAttrs = Object.keys(optionsProps).map( (name) => `data-${kebabCase(name)}` ); Object.keys(optionsProps).forEach((name) => { const attrName = `data-${kebabCase(name)}`; if (el.hasAttribute(attrName)) { component.options[name] = el.getAttribute(attrName); } }); let attrObserver = new MutationObserver((mutationsList) => { for (const mutation of mutationsList) { if ( mutation.type !== "attributes" || !optionsAttrs.includes(mutation.attributeName) ) { return; } const propName = camelCase(mutation.attributeName.replace("data-", "")); let value = mutation.target.getAttribute(mutation.attributeName); switch (value) { case "true": value = true; break; case "false": value = false; break; } component.options[propName] = value; } }); Object.assign( component, Alpine.reactive({ destroy() { attrObserver.disconnect(); attrObserver = null; if (oldDestroy) { oldDestroy.call(this); } }, }) ); attrObserver.observe(el, { attributes: true }); component.$watch("options", (options, oldOptions) => { for (const [key, value] of Object.entries(options)) { el.setAttribute(`data-${kebabCase(key)}`, value); if (component.onOptionChange) { component.onOptionChange(key, value); } } }); return component; }; }
Version data entries
16 entries across 16 versions & 1 rubygems