Add an abortable listener
This example demonstrates how to add an addEventListener() that can be aborted with an AbortSignal.HTML
HTMLPlayCopy to Clipboard<table id="outside">
<tr>
<td id="t1">one</td>
</tr>
<tr>
<td id="t2">two</td>
</tr>
</table>
JavaScript
JSPlayCopy to Clipboard// Add an abortable event listener to table
const controller = new AbortController();
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, { signal: controller.signal });
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue === "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
controller.abort(); // remove listener after value reaches "three"
}
}
In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call abort() from the AbortController we passed to the addEventListener() call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event.
Result
PlayEvent listener with anonymous function
Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener.HTML
HTMLPlayCopy to Clipboard<table id="outside">
<tr>
<td id="t1">one</td>
</tr>
<tr>
<td id="t2">two</td>
</tr>
</table>