Fix x-if sub expressions still being evaluated after x-if evals to false #2556
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi There!
This PR is to address an issue where after an
<template x-if="expression"></template>
has evaluated to false and thus the DOM element has been removed, sub expressions are still evaluated. Example reports of this issue are: #2540 #2296 #1837 #1917Imagine the following code:
Before the suggested fix the above code would produce the following when "Logout" is clicked:
This is because of the following pseudo timeline:
user
is set tonull
effect()
on thex-text
directive to queue an expression evaluation i.euser.name
.x-if="user"
expression is evaluated and the result is now false. The cleanup tasks run and removes the<span></span>
element from the DOM.user.name
throws an exception.My solution is to simply remove the queued effect from the queue in the
el._x_undoIf()
method call. I am however not sure how maintainers will feel about exposing a new method inscheduler.js
though. I could not determine a better way though.This was my first peek into the internals of Alpine so there very well may be a better way to solve this issue. I added a new Cypress test to demonstrate this bug and to also demonstrate how this solution fixes the bug.
Very open to feedback on a better solution.