Sha256: 83968477e0bf295a7aba999cbf4286cba44fc4fdffc0c89614085adf175664b5

Contents?: true

Size: 1.31 KB

Versions: 16

Compression:

Stored size: 1.31 KB

Contents

const ignoredAttributes = ["class", "style"];

export default function withAttrObserver(props = {}) {
  return function (component) {
    const oldDestroy = component.destroy;
    const toIgnore = props.ignore || ignoredAttributes;

    const attrObserver = Alpine.reactive({
      observer: null,
      handler(attrName, newValue, oldValue, target) {
        if (component.onAttrChange) {
          component.onAttrChange(attrName, newValue, oldValue, target);
        }
      },
    });

    attrObserver.observer = new MutationObserver((mutationsList) => {
      for (const mutation of mutationsList) {
        if (
          mutation.type !== "attributes" ||
          toIgnore.includes(mutation.attributeName)
        ) {
          return;
        }

        const { target } = mutation;

        attrObserver.handler(
          mutation.attributeName,
          target.getAttribute(mutation.attributeName),
          mutation.oldValue,
          target
        );
      }
    });

    Object.assign(component, {
      destroy() {
        attrObserver.observer.disconnect();
        attrObserver.observer = null;

        if (oldDestroy) {
          oldDestroy.call(this);
        }
      },
    });

    attrObserver.observer.observe(component.$root, { attributes: true });

    return component;
  };
}

export { ignoredAttributes };

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
coveragebook_components-0.7.1 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.7.0 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.5 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.4 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.3 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.2 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.1 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.6.0 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.7 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.6 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.5 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.4 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.3 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.2 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.1 app/assets/js/base/mixins/attr-observer.js
coveragebook_components-0.5.0 app/assets/js/base/mixins/attr-observer.js