Skip to content

Commit

Permalink
feat(EventBus): 新增 clear, destroy
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 18, 2021
1 parent 5ece08c commit 38558f6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
15 changes: 15 additions & 0 deletions src/utils/EventBus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,19 @@ describe('EventBus', () => {
expect(errorCallback).toBeCalled().toBeCalledTimes(2)
expect(errorCallback2).toBeCalled().toBeCalledTimes(2)
})

test('支持 clear', () => {
const bus = new EventBus<{
test: () => any
}>()
const fn = jest.fn()
bus.on('test', fn)
bus.emit('test')
expect(fn).toBeCalled().toBeCalledTimes(1)
bus.emit('test')
expect(fn).toBeCalled().toBeCalledTimes(2)
bus.clear()
bus.emit('test')
expect(fn).toBeCalled().toBeCalledTimes(2)
})
})
19 changes: 17 additions & 2 deletions src/utils/EventBus.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export type EventBusListenerTag = string | number

export type EventBusListener<
TCallback extends (...args: any[]) => any = (...args: any[]) => any
TCallback extends (...args: any[]) => any = (...args: any[]) => any,
> = TCallback & {
__EVENT_BUS_TAG__?: EventBusListenerTag
}
Expand All @@ -11,7 +11,7 @@ export type EventBusOffListener = () => any
export type EventBusListeners = Record<string, EventBusListener>

export interface EventBusListenerDescriptor<
TListenerName extends keyof EventBusListeners
TListenerName extends keyof EventBusListeners,
> {
name: TListenerName
context?: any
Expand Down Expand Up @@ -176,4 +176,19 @@ export class EventBus<TListeners extends EventBusListeners> {
return callback.call(context, ...args)
})
}

/**
* 清空事件订阅。
*/
clear() {
this.callbacks = Object.create(null)
}

/**
* 销毁。
*/
destroy() {
// @ts-ignore
this.callbacks = null
}
}

0 comments on commit 38558f6

Please sign in to comment.