Skip to content

Commit 6495727

Browse files
authored
document Abortcontroller with addEventListener
1 parent 51f3530 commit 6495727

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

docs/_guide/patterns.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,36 @@ class RemoveSearchElement extends HTMLElement {
7070
}
7171
}
7272
```
73+
74+
### Registering global or many event listeners
75+
76+
Generally speaking, you'll want to use ["Actions"]({{ site.baseurl }}/guide/actions) to register event listeners with your Controller, but Actions only work for components nested within your Controller. It may also be necessary to listen for events on the Document, Window, or across well-known adjacent elements. We can manually call `addEventListener` for these types, including during the `connectedCallback` phase. Cleanup for `addEventListener` can be a bit error prone, but `AbortController` can be useful here to pass a signal that the element is cleaning up:
77+
78+
79+
```typescript
80+
@controller
81+
class UnsavedChangesElement extends HTMLElement {
82+
83+
#eventAbortController: AbortController|null
84+
85+
connectedCallback(event: Event) {
86+
// Create the new AbortController and get the new signal
87+
const {signal} = (this.#eventAbortController = new AbortController())
88+
89+
// You can `signal` as an option to any `addEventListener` call:
90+
window.addEventListener('hashchange', this, { signal })
91+
window.addEventListener('blur', this, { signal })
92+
window.addEventListener('popstate', this, { signal })
93+
window.addEventListener('pagehide', this, { signal })
94+
}
95+
96+
disconnectedCallback() {
97+
// This will clean up any `addEventListener` calls which were given the `signal`
98+
this.#eventAbortController?.abort()
99+
}
100+
101+
handleEvent(event) {
102+
// ...
103+
}
104+
}
105+
```

0 commit comments

Comments
 (0)