Add Methods to Remove Listeners for Built-In Events
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
## Background and Motivation
The JavaScript SignalR client package allows adding event listeners for built-in events via e.g. the `HubConnection.onclose` method. However, unlike with the `HubConnection.off` method for custom events, the `HubConnection` class does not provide a way to remove these event listeners. This presents a problem when a callback registered as an event listener should not persist for the entire lifetime of the connection.
I propose adding methods to remove individual or all event listeners for each built-in event, similar to the existing API for custom events.
## Proposed API
The `HubConnection` class could be extended as follows:
```diff
class HubConnection {
+ // Remove all event listeners for the event type.
+ public offclose(): void;
+
+ // Remove a specific event listener.
+ public offclose(method: (...args: any[]) => void): void;
}
```
The same additions should be made for the `onreconnecting` and `onreconnected` methods.
## Usage Examples
The following example uses React, as it is the most prevalent front-end technology.
```tsx
function MyPage() {
// Add an event listener when the page first renders.
useEffect(() => {
connection.onreconnected(() => { /* Do something... */ });
return () => {
// Remove the event listener when the user navigates to a different page.
connection.offreconnected();
};
}, []);
}
```
## Alternative Designs
The proposed API is based on existing methods for removing event listeners for custom events.
## Risks
The addition of these new methods does not affect any existing usage of the library.
Contributor guide
Assessment
This issue has not been assessed yet.