-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add 'disconnect' event for the webHID device
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
export class GlobalDisconnectListener { | ||
private static listeners = new Map<HIDDevice, () => void>() | ||
private static isSetup = false | ||
|
||
/** Add listener for disconnect event, for a HIDDevice. The callback will be fired once. */ | ||
static listenForDisconnect(device: HIDDevice, callback: () => void) { | ||
this.setup() | ||
this.listeners.set(device, callback) | ||
} | ||
|
||
private static setup() { | ||
if (this.isSetup) return | ||
navigator.hid.addEventListener('disconnect', this.handleDisconnect) | ||
this.isSetup = true | ||
} | ||
private static handleDisconnect = (ev: HIDConnectionEvent) => { | ||
this.listeners.forEach((callback, device) => { | ||
if (device === ev.device) { | ||
callback() | ||
// Also remove the listener: | ||
this.listeners.delete(device) | ||
} | ||
}) | ||
if (this.listeners.size === 0) { | ||
// If there are not listeners, we can teardown the global listener: | ||
this.teardown() | ||
} | ||
} | ||
private static teardown() { | ||
navigator.hid.removeEventListener('disconnect', this.handleDisconnect) | ||
this.listeners.clear() | ||
this.isSetup = false | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters