Skip to content

Commit 91ee549

Browse files
committed
feat: add offListener method
1 parent 38898c6 commit 91ee549

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+18
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ parentPort.onMessage('ack', payload => {
121121
path: ' /',
122122
});
123123
});
124+
125+
// 4. If you want to remove some listeners
126+
const handleAck = (payload) => {
127+
console.log('[parent] [syn]');
128+
};
129+
parentPort.onMessage('ack', handleAck);
130+
parentPort.offListener('ack', handleAck);
131+
// Note: if the second param of `offListener` is omitted, all listeners will be removed.
132+
parentPort.offMessage('ack');
124133
```
125134

126135
3. Child process implementation:
@@ -154,6 +163,15 @@ childPort.onMessage('syn', payload => {
154163
childPort.onMessage('body', payload => {
155164
console.log('[child] [body]', JSON.stringify(payload));
156165
});
166+
167+
// 4. If you want to remove some listeners by `offMessage`
168+
const handleSyn = (payload) => {
169+
console.log('[child] [syn]');
170+
};
171+
childPort.onMessage('syn', handleSyn);
172+
childPort.offListener('syn', handleSyn);
173+
// Note: if the second param of `offListener` is omitted, all listeners will be removed.
174+
childPort.offMessage('syn');
157175
```
158176

159177
## 📖 Basic Concepts

src/index.ts

+18
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ interface Port<T extends MessageDefinition, D extends Direction<T>> {
116116
t: U,
117117
handler: Callback<[Payload<T, ReverseDirection<T, D>, U>]>,
118118
): void;
119+
offListener<U extends keyof T[ReverseDirection<T, D>]>(
120+
t: U,
121+
handler?: Callback<[Payload<T, ReverseDirection<T, D>, U>]>,
122+
): void;
119123
}
120124

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

265+
public offListener: Port<T, InferDirectionByPort<T, U>>['offListener'] = (t, handler) => {
266+
if (!this.handlers[t]) {
267+
return;
268+
}
269+
if (handler) {
270+
this.handlers[t] = this.handlers[t].filter(h => h !== handler);
271+
if (this.handlers[t].length === 0) {
272+
delete this.handlers[t];
273+
}
274+
} else {
275+
delete this.handlers[t];
276+
}
277+
};
278+
261279
public destroy() {
262280
this.handlers = {};
263281
this.channel?.destroy && this.channel.destroy();

0 commit comments

Comments
 (0)