Skip to content

Commit

Permalink
Add unsubscribe function to event listener (#35)
Browse files Browse the repository at this point in the history
* Use unsubscribe function to remove listener

* Fix linting issues

* fix incorrect time dayjs function in status indicator

* rename data to profileData to reflect changes in the space library
  • Loading branch information
Peter Maguire authored Mar 23, 2023
1 parent 87c1c12 commit f0467b4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
15 changes: 15 additions & 0 deletions src/Space.mockClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ describe('Space (mockClient)', () => {
expect(spy).toHaveBeenCalledOnce();
});

it<SpaceTestContext>('returns an unsubscribe function', async ({ space }) => {
let unsubscribeFunc = space.on('membersUpdate', () => {});
expect(unsubscribeFunc).toBeTypeOf('function');
});

it<SpaceTestContext>('errors if an unrecognized event is passed in', async ({ space }) => {
await space.enter();
// @ts-expect-error
Expand Down Expand Up @@ -329,6 +334,16 @@ describe('Space (mockClient)', () => {

expect(callbackSpy).toHaveBeenCalledTimes(4);
});

it<SpaceTestContext>('unsubscribes when the unsubscribe function is called', async ({ space }) => {
const spy = vi.fn();
const unsubscribeFunc = space.on('membersUpdate', spy);
space.dispatchEvent(createPresenceEvent('enter', { clientId: '123456' }));
unsubscribeFunc();
space.dispatchEvent(createPresenceEvent('enter', { clientId: '123456' }));

expect(spy).toHaveBeenCalledOnce();
});
});
});
});
12 changes: 9 additions & 3 deletions src/Space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const SPACE_CHANNEL_PREFIX = '_ably_space_';

type SpaceEvents = 'membersUpdate';

type UnsubscribeFunc = () => void;

export type SpaceMember = {
clientId: string;
isConnected: boolean;
Expand Down Expand Up @@ -169,10 +171,10 @@ class Space extends EventTarget {
return this.channel.presence.leave(data);
}

on(spaceEvent: SpaceEvents, callback) {
on(spaceEvent: SpaceEvents, callback): UnsubscribeFunc {
if (spaceEvent === 'membersUpdate') {
this.subscribeToPresence();
this.addEventListener('membersUpdate', (event: SpaceMembersUpdateEvent) => {
const eventListener = (event: SpaceMembersUpdateEvent) => {
if (!event.message) return;
// By default, we only return data about other connected clients, not the whole set
if (event.message.clientId === this.clientId) return;
Expand All @@ -185,7 +187,11 @@ class Space extends EventTarget {
}

callback(this.members);
});
};
this.addEventListener('membersUpdate', eventListener);
return () => {
this.removeEventListener('membersUpdate', eventListener);
};
} else {
// TODO: align with ably-js error policy here
throw new Error(`Event "${spaceEvent}" is unsupported`);
Expand Down

0 comments on commit f0467b4

Please sign in to comment.