Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle special binding case for 'checked' and 'selected' #3535

Merged
merged 2 commits into from
May 10, 2023

Conversation

inxilpro
Copy link
Contributor

I ran into an interesting issue with x-bind and the checked property today. Here's the Twitter thread summarizing the issue, and here's a codesandbox demo showing it in action.

Basically, the value, checked and selected properties are special in that they're not kept in sync with their corresponding attributes. That means that the following is perfectly legit javascript:

element.setAttribute('checked', 'checked');
element.checked = false;

This will result in a checkbox that is not checked, but has a checked attribute set (which, as far as I can tell, is visually checked but not "technically" checked).

Anyway, 90% of the time this won't come up because both x-bind:value and x-model have special bind logic for checkbox values that set the property rather than the attribute:

if (Array.isArray(value)) {
el.checked = value.some(val => checkedAttrLooseCompare(val, el.value))
} else {
el.checked = !!value
}

There are some cases, though, where you want to handle both sides of the binding on your own (in our case, the checkboxes are driven from Algolia instant search state, so changing the checkbox triggers an event that then updates the state). This PR makes that case possible.

packages/alpinejs/src/utils/bind.js Outdated Show resolved Hide resolved
packages/alpinejs/src/utils/bind.js Outdated Show resolved Hide resolved
Co-authored-by: Eric Kwoka <43540491+ekwoka@users.noreply.github.com>
@calebporzio
Copy link
Collaborator

Thanks @inxilpro!

@calebporzio calebporzio merged commit 36156c2 into alpinejs:main May 10, 2023
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.

3 participants