79420785

Date: 2025-02-07 11:55:33
Score: 0.5
Natty:
Report link

Yes! You can achieve this in Alpine.js without a MutationObserver by using Alpine’s built-in @attr directive. This allows you to reactively update fooEnabled when the data-foo attribute is added or removed.

<div x-data="{ fooEnabled: false }">
  <button @click="fooEnabled = !fooEnabled; fooEnabled ? $el.setAttribute('data-foo', '123') : $el.removeAttribute('data-foo')">
    Toggle data-foo
  </button>
  <p x-text="fooEnabled ? 'Enabled' : 'Disabled'"></p>
</div>

@attr:data-foo.window is triggered whenever the data-foo attribute changes. Inside the handler, we check if data-foo exists using $el.hasAttribute('data-foo'), then update fooEnabled accordingly.

This is a clean and simple Alpine.js solution without needing an external MutationObserver.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @attr
  • Low reputation (0.5):
Posted by: Mani Shankar Mandal