Skip to content

Commit

Permalink
feat: add offListener method
Browse files Browse the repository at this point in the history
  • Loading branch information
sanyuan0704 committed Jul 29, 2024
1 parent 38898c6 commit c808d10
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ parentPort.onMessage('ack', payload => {
path: ' /',
});
});

// 4. If you want to remove some listeners
parentPort.offListener('ack');
```

3. Child process implementation:
Expand Down Expand Up @@ -154,6 +157,13 @@ childPort.onMessage('syn', payload => {
childPort.onMessage('body', payload => {
console.log('[child] [body]', JSON.stringify(payload));
});

// 4. If you want to remove some listeners by `offMessage`
const handleSyn = (payload) => {
console.log('[child] [syn]');
};
childPort.onMessage('syn', handleSyn);
childPort.offListener('syn', handleSyn);
```

## 📖 Basic Concepts
Expand Down
18 changes: 18 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ interface Port<T extends MessageDefinition, D extends Direction<T>> {
t: U,
handler: Callback<[Payload<T, ReverseDirection<T, D>, U>]>,
): void;
offListener<U extends keyof T[ReverseDirection<T, D>]>(
t: U,
handler?: Callback<[Payload<T, ReverseDirection<T, D>, U>]>,
): void;
}

export type EnsureString<T> = T extends string ? T : never;
Expand Down Expand Up @@ -258,6 +262,20 @@ export class Unport<
this.handlers[t].push(handler);
};

public offListener: Port<T, InferDirectionByPort<T, U>>['offListener'] = (t, handler) => {
if (!this.handlers[t]) {
return;
}
if (handler) {
this.handlers[t] = this.handlers[t].filter(h => h !== handler);
if (this.handlers[t].length === 0) {
delete this.handlers[t];
}
} else {
delete this.handlers[t];
}
};

public destroy() {
this.handlers = {};
this.channel?.destroy && this.channel.destroy();
Expand Down

0 comments on commit c808d10

Please sign in to comment.