Skip to content

Commit 6f595c3

Browse files
authored
Merge pull request #185 from github/document-abortcontroller-with-addeventlistener
document Abortcontroller with addEventListener
2 parents 6633678 + d1378a1 commit 6f595c3

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

docs/_guide/patterns.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,37 @@ class RemoveSearchElement extends HTMLElement {
9393
}
9494
}
9595
```
96+
97+
### Registering global or many event listeners
98+
99+
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`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) can be useful here to pass a signal that the element is cleaning up:
100+
101+
102+
```typescript
103+
@controller
104+
class UnsavedChangesElement extends HTMLElement {
105+
106+
#eventAbortController: AbortController|null
107+
108+
connectedCallback(event: Event) {
109+
// Create the new AbortController and get the new signal
110+
const {signal} = (this.#eventAbortController = new AbortController())
111+
112+
// You can `signal` as an option to any `addEventListener` call:
113+
window.addEventListener('hashchange', this, { signal })
114+
window.addEventListener('blur', this, { signal })
115+
window.addEventListener('popstate', this, { signal })
116+
window.addEventListener('pagehide', this, { signal })
117+
}
118+
119+
disconnectedCallback() {
120+
// This will clean up any `addEventListener` calls which were given the `signal`
121+
this.#eventAbortController?.abort()
122+
}
123+
124+
handleEvent(event) {
125+
// `handleEvent` will be called when each one of the event listeners
126+
// defined in `connectedCallback` is dispatched.
127+
}
128+
}
129+
```

0 commit comments

Comments
 (0)