Skip to content
Merged
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,24 @@ es.addEventListener("error", (event) => {
}
});

es.addEventListener("done", (event) => {
console.log("Done SSE connection.");
});

es.addEventListener("close", (event) => {
console.log("Close SSE connection.");
});
```

### Done vs Close

`done` events will fire when server closes the connection.
By default, the client will automatically reconnect when this happens.
You can disable reconnections by setting the `pollingInterval` option to `0`.
`close` events will fire when the connection is terminated by the client, using `.close()`.

### Headers and params

If you want to use Bearer token and/or topics, look at this example (TypeScript):

```typescript
Expand Down
7 changes: 6 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type BuiltInEventType = 'open' | 'message' | 'error' | 'close';
export type BuiltInEventType = 'open' | 'message' | 'error' | 'done' | 'close';
export type EventType<E extends string = never> = E | BuiltInEventType;

export interface MessageEvent {
Expand All @@ -12,6 +12,10 @@ export interface OpenEvent {
type: 'open';
}

export interface DoneEvent {
type: 'done';
}

export interface CloseEvent {
type: 'close';
}
Expand Down Expand Up @@ -55,6 +59,7 @@ export interface EventSourceOptions {
type BuiltInEventMap = {
'message': MessageEvent,
'open': OpenEvent,
'done': DoneEvent,
'close': CloseEvent,
'error': ErrorEvent | TimeoutEvent | ExceptionEvent,
};
Expand Down
2 changes: 2 additions & 0 deletions src/EventSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class EventSource {
open: [],
message: [],
error: [],
done: [],
close: [],
};

Expand Down Expand Up @@ -117,6 +118,7 @@ class EventSource {
if (xhr.readyState === XMLHttpRequest.DONE) {
this._logDebug('[EventSource][onreadystatechange][DONE] Operation done.');
this._pollAgain(this.interval, false);
this.dispatch('done', { type: 'done' });
}
} else if (xhr.status !== 0) {
this.status = this.ERROR;
Expand Down