ข้ามไปยังเนื้อหา

Actions

บางครั้งคุณต้องการเข้าถึง DOM node แบบ imperative — เพื่อ init charting library, trap focus, ตั้ง tooltip หรือ detect click นอก element action ห่อ logic นั้นเป็นฟังก์ชันที่ reuse ได้ ผูกด้วย use: directive

action คือฟังก์ชันที่รับ DOM node (และพารามิเตอร์ optional) ตอน element mount และอาจ return object ที่มี method update และ destroy:

<script>
// action: (node, params?) => { update?, destroy? }
function tooltip(node, text) {
const el = document.createElement('div');
el.className = 'tooltip';
el.textContent = text;
function show() { document.body.appendChild(el); }
function hide() { el.remove(); }
node.addEventListener('mouseenter', show);
node.addEventListener('mouseleave', hide);
return {
update(newText) { el.textContent = newText; }, // params เปลี่ยน
destroy() { // element กำลัง unmount
node.removeEventListener('mouseenter', show);
node.removeEventListener('mouseleave', hide);
el.remove();
},
};
}
</script>
<button use:tooltip={'Save your work'}>Save</button>
flowchart LR
  mount["element mount"] --> run["action(node, params) run"]
  run --> update["params เปลี่ยน → update(newParams)"]
  update --> update
  update --> destroy["element unmount → destroy()"]
action lifecycle

action เด่นมากสำหรับ behavior DOM ที่ cross-cutting action clickOutside dispatch เมื่อ click ลงนอก node — เหมาะสำหรับปิด dropdown และ modal:

<script>
function clickOutside(node, callback) {
function handle(e) {
if (!node.contains(e.target)) callback();
}
document.addEventListener('click', handle, true);
return {
destroy() { document.removeEventListener('click', handle, true); },
};
}
let open = $state(false);
</script>
{#if open}
<div class="menu" use:clickOutside={() => (open = false)}></div>
{/if}

คุณ อาจ ทำบางส่วนนี้ด้วย bind:this บวก $effect action ดีกว่าเมื่อ behavior นั้น reuse ได้ข้าม element และ self-contained (setup + teardown ในที่เดียว): method destroy การันตี cleanup และการส่งพารามิเตอร์ด้วย use:action={params} ทำให้ declarative ที่จุดเรียก หยิบ action มาใช้เมื่อคุณอยากบอกว่า “element นี้ behave เหมือน X” และ reuse X ได้ทุกที่

ฟังก์ชัน action รับอะไรตอน element mount?
method `destroy` ของ action ทำอะไร?
เมื่อไร action เหมาะกว่า `bind:this` + `$effect`?
ผูก action พร้อมพารามิเตอร์เข้ากับ element ยังไง?