Skip to content

Added clarification to phx-remove to explain a surprising behavior#3800

Open
pinetops wants to merge 1 commit intophoenixframework:mainfrom
pinetops:features/phx_remove_doc_update
Open

Added clarification to phx-remove to explain a surprising behavior#3800
pinetops wants to merge 1 commit intophoenixframework:mainfrom
pinetops:features/phx_remove_doc_update

Conversation

@pinetops
Copy link
Copy Markdown

I would like to make sure no-one else has to chase down this issue.

I'm not sure that I can quite explain the exact circumstances that phx-remove will fire/not fire, but I think that making sure the parent has a DOM ID is a good practice to make sure you don't have any problems.

@pinetops pinetops force-pushed the features/phx_remove_doc_update branch from 668f815 to 7c4ebad Compare May 14, 2025 17:35
@SteffenDE
Copy link
Copy Markdown
Collaborator

Hey @pinetops,

I'm not sure if this is a good clarification. phx-remove is a bit tricky, since it is only executed when morphdom decides to remove a node and that node also has phx-remove set. This means that:

  1. a node that is updated into another one is not removed, therefore phx-remove is not called:

    Imagine we go from this HTML

    <ul>
      <li phx-remove="...">A</li>
      <li phx-remove="...">B</li>
      <li phx-remove="...">C</li>
    </ul>

    to that

    <ul>
      <li phx-remove="...">A</li>
      <li phx-remove="...">C</li>
      <li phx-remove="...">D</li>
    </ul>

    We might say that we removed the B node and added a D node, but for morphdom it would be an update of the innerText of the second child from B to C and the third child from C to D. A good way to ensure that nodes are discarded is to give them unique IDs:

    <ul>
      <li id="a" phx-remove="...">A</li>
      <li id="b" phx-remove="...">B</li>
      <li id="c" phx-remove="...">C</li>
    </ul>

    If we now update this to A, C, D, morphdom would be forced to remove B.

  2. phx-remove is only called on the removed element, not on children. So even when we have the example from above, if the whole <ul> is removed, phx-remove on an individual <li> would not be called.

Do you have a code example for the case you described?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants