Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(websocket): add ability to remove listener #2027

Open
wants to merge 9 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/cleanup-fn-websocket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
websocket-js: minor
websocket: minor
---

`addListener` now returns a cleanup function instead of `void` to remove the listener.
2 changes: 1 addition & 1 deletion plugins/websocket/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 9 additions & 5 deletions plugins/websocket/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ export type Message =

export default class WebSocket {
id: number
private readonly listeners: Array<(arg: Message) => void>
private readonly listeners: Set<(arg: Message) => void>

constructor(id: number, listeners: Array<(arg: Message) => void>) {
constructor(id: number, listeners: Set<(arg: Message) => void>) {
this.id = id
this.listeners = listeners
}
Expand All @@ -69,7 +69,7 @@ export default class WebSocket {
url: string,
config?: ConnectionConfig
): Promise<WebSocket> {
const listeners: Array<(arg: Message) => void> = []
const listeners: Set<(arg: Message) => void> = new Set()

const onMessage = new Channel<Message>()
onMessage.onmessage = (message: Message): void => {
Expand All @@ -89,8 +89,12 @@ export default class WebSocket {
}).then((id) => new WebSocket(id, listeners))
}

addListener(cb: (arg: Message) => void): void {
this.listeners.push(cb)
addListener(cb: (arg: Message) => void): () => void {
this.listeners.add(cb)

return () => {
this.listeners.delete(cb)
}
}

async send(message: Message | string | number[]): Promise<void> {
Expand Down
Loading