المفتاح
ربط LiveView
<div class="flex flex-wrap gap-2 mb-4">
<.action phx-click={Corex.Switch.set_checked("switch-api-cb", true)} class="button button--sm">On</.action>
<.action phx-click={Corex.Switch.set_checked("switch-api-cb", false)} class="button button--sm">Off</.action>
<.action phx-click={Corex.Switch.toggle_checked("switch-api-cb")} class="button button--sm">Toggle</.action>
</div>
<.switch class="switch">
<:label>Power</:label>
</.switch>
JS العميل
<div class="flex flex-wrap gap-2 mb-4">
<button
type="button"
class="button button--sm"
onclick="document.getElementById('switch-api-cjs')?.dispatchEvent(new CustomEvent('corex:switch:set-checked', {bubbles: false, detail: { checked: true } }))"
>
On
</button>
<button
type="button"
class="button button--sm"
onclick="document.getElementById('switch-api-cjs')?.dispatchEvent(new CustomEvent('corex:switch:set-checked', {bubbles: false, detail: { checked: false } }))"
>
Off
</button>
<button
type="button"
class="button button--sm"
onclick="document.getElementById('switch-api-cjs')?.dispatchEvent(new CustomEvent('corex:switch:toggle-checked', { bubbles: false }))"
>
Toggle
</button>
</div>
<.switch class="switch">
<:label>Power</:label>
</.switch>
const el = document.getElementById("switch-api-cjs");
el?.dispatchEvent(
new CustomEvent("corex:switch:set-checked", { bubbles: false, detail: { checked: true } })
);
el?.dispatchEvent(
new CustomEvent("corex:switch:set-checked", { bubbles: false, detail: { checked: false } })
);
el?.dispatchEvent(new CustomEvent("corex:switch:toggle-checked", { bubbles: false }));
const el: HTMLElement | null = document.getElementById("switch-api-cjs");
el?.dispatchEvent(
new CustomEvent("corex:switch:set-checked", { bubbles: false, detail: { checked: true } })
);
el?.dispatchEvent(
new CustomEvent("corex:switch:set-checked", { bubbles: false, detail: { checked: false } })
);
el?.dispatchEvent(new CustomEvent("corex:switch:toggle-checked", { bubbles: false }));
دفع من الخادم
<div class="flex flex-wrap gap-2 mb-4">
<.action phx-click="switch_api_on" class="button button--sm">On</.action>
<.action phx-click="switch_api_off" class="button button--sm">Off</.action>
<.action phx-click="switch_api_toggle" class="button button--sm">Toggle</.action>
</div>
<.switch class="switch">
<:label>Power</:label>
</.switch>
def handle_event("switch_api_on", _params, socket) do
{:noreply, Corex.Switch.set_checked(socket, "switch-api-srv", true)}
end
def handle_event("switch_api_off", _params, socket) do
{:noreply, Corex.Switch.set_checked(socket, "switch-api-srv", false)}
end
def handle_event("switch_api_toggle", _params, socket) do
{:noreply, Corex.Switch.toggle_checked(socket, "switch-api-srv")}
end