How are people setting the indeterminate
flag on a checkbox in LiveView?
I looked at adding a Hook with a MutationObserver on a data-attribute I set for it, but that seems like a lot.
Is there an easier way I missed?
Thanks
How are people setting the indeterminate
flag on a checkbox in LiveView?
I looked at adding a Hook with a MutationObserver on a data-attribute I set for it, but that seems like a lot.
Is there an easier way I missed?
Thanks
The element’s hook can simply be triggered when:
mounted
- the element has been added to the DOM and its server LiveView has finished mounting
https://hexdocs.pm/phoenix_live_view/0.19.2/js-interop.html#client-hooks-via-phx-hook
<input id="foo" type="checkbox" phx-hook="Indeterminate" />
Hooks.Indeterminate = {
mounted() {
this.el.indeterminate = true;
},
};
What about when you want to set indeterminate
in response to some server side event?
def handle_event("foo", _params, socket) do
{:noreply, assign(socket, indeterminate: is_indeterminate?()}
end
I tried doing something like…
<.input id="check-all" name="check-all" type="checkbox" value={false} phx-hook={@indeterminate && "Indeterminate"} />
But the hook wasn’t triggering at all, despite having mounted
and updated
keys.
You can use push_event/3.
To trigger the JS hook from server to client, see this link.
For example, we can add this addition to the JS hook:
Hooks.Indeterminate = {
mounted() {
this.el.indeterminate = true;
+ this.handleEvent(
+ "set-indeterminate",
+ (data) => (this.el.indeterminate = data.value)
+ );
},
};
And then trigger that addition like so:
def handle_event("foo", _, socket) do
{:noreply, push_event(socket, "set-indeterminate", %{value: true})}
end
It should also be doable via a window event listener
I hope this helps!
Awesome, thank you! That’s exactly what I was looking for, but for some reason I overlooked it and only saw the other direction, JS.push to server.