addPathIdsListener
The addPathIdsListener
method registers a listener function with the WsServer
that will be called whenever there is a change in the active paths that a WsServer
is handling.
addPathIdsListener(listener: PathIdsListener): string
Type | Description | |
---|---|---|
listener | PathIdsListener | The function that will be called whenever the path |
returns | string | A unique |
The provided listener is a PathIdsListener
function, and will be called with a reference to the WsServer
and a callback you can use to get information about the change.
Example
This example creates a WsServer
, and listens to changes to the active paths when clients connect to and disconnect from it.
import {WebSocket, WebSocketServer} from 'ws';
import {createMergeableStore} from 'tinybase';
import {createWsServer} from 'tinybase/synchronizers/synchronizer-ws-server';
import {createWsSynchronizer} from 'tinybase/synchronizers/synchronizer-ws-client';
const server = createWsServer(new WebSocketServer({port: 8047}));
const listenerId = server.addPathIdsListener(
(server, pathId, addedOrRemoved) => {
console.log(pathId + (addedOrRemoved == 1 ? ' added' : ' removed'));
console.log(server.getPathIds());
},
);
const synchronizer1 = await createWsSynchronizer(
createMergeableStore(),
new WebSocket('ws://localhost:8047/roomA'),
);
// -> 'roomA added'
// -> ['roomA']
const synchronizer2 = await createWsSynchronizer(
createMergeableStore(),
new WebSocket('ws://localhost:8047/roomB'),
);
// -> 'roomB added'
// -> ['roomA', 'roomB']
synchronizer1.destroy();
// ...
// -> 'roomA removed'
// -> ['roomB']
synchronizer2.destroy();
// ...
// -> 'roomB removed'
// -> []
server.delListener(listenerId);
server.destroy();
Since
v5.0.0