Alpine: Strange behavior when reparenting component

Created on 1 May 2020  路  5Comments  路  Source: alpinejs/alpine

Example (note the .js tab too)

My use case is showing a toolbar in a list of items. Instead of generating toolbar HTML for each and every item, I want to reparent a single instance when the user hovers over an item.

Unfortunately, when I try to add Alpine, it seems like it creates a new internal instance every time the element gets reparented. The console log gets executed more and more, and the state keeps getting reset back to its original.

Is there a way for Alpine to uniquely identify a component across reparenting? Perhaps an x-key like React? Or maybe it should look at an element's id if it has one?

Most helpful comment

so... The issue is here -> https://github.com/alpinejs/alpine/blob/master/src/component.js#L355

This change would fix it: https://github.com/alpinejs/alpine/compare/master...SimoTod:bug/mutation-observer-resets-nested-component?expand=1
I've no idea how to write a good test for it, so here you go:
https://codepen.io/SimoTod/pen/qBOPoZy

All 5 comments

Hi @gilbert, this is the nature of how Alpine observes the DOM currently. Each time you move the element, the MutationObserver picks it up and will re-initialise that element.

It's weird though, the mutation observer should not reinitialise an element if it has already a __x property attached like in this case so reparenting should be possible. (https://github.com/alpinejs/alpine/blob/master/src/index.js#L78). It sounds like a bug. I'll see if I can dive into it later or during the weekend.

It's weird though, the mutation observer should not reinitialise an element if it has already a __x property attached like in this case so reparenting should be possible. (https://github.com/alpinejs/alpine/blob/master/src/index.js#L78). It sounds like a bug. I'll see if I can dive into it later or during the weekend.

Ah right I see. The same node is being moved around, does sound like a bug then.

I have the feeling that it could be the internal mutation observer (inside the component) thinking that x-data (html attribute) has changed and resetting everything.

so... The issue is here -> https://github.com/alpinejs/alpine/blob/master/src/component.js#L355

This change would fix it: https://github.com/alpinejs/alpine/compare/master...SimoTod:bug/mutation-observer-resets-nested-component?expand=1
I've no idea how to write a good test for it, so here you go:
https://codepen.io/SimoTod/pen/qBOPoZy

Was this page helpful?
0 / 5 - 0 ratings