dotnet / dotnet/aspnetcore

Add Methods to Remove Listeners for Built-In Events

Open
#66,706 3 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-signalr feature-request
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.