Skip to content

Commit

Permalink
feat(EventBus): 支持 filter 过滤回调
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 26, 2024
1 parent 0a231a4 commit 8290e32
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/utils/EventBus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,48 @@ describe('EventBus', () => {
bus.emit('test')
expect(fn).toBeCalled().toBeCalledTimes(2)
})

test('支持 filter', () => {
const bus = new EventBus<{
test: () => any
}>()
const fn = jest.fn()
const fn1 = jest.fn()
const fn2 = jest.fn()

bus.on('test', fn)
bus.on('test', fn1)
bus.on('test', fn2)

bus.emit({
name: 'test',
})
expect(fn).toBeCalled().toBeCalledTimes(1)
expect(fn1).toBeCalled().toBeCalledTimes(1)
expect(fn2).toBeCalled().toBeCalledTimes(1)

bus.emit({
name: 'test',
filter: (_, index) => index === 0,
})
expect(fn).toBeCalled().toBeCalledTimes(2)
expect(fn1).toBeCalled().toBeCalledTimes(1)
expect(fn2).toBeCalled().toBeCalledTimes(1)

bus.emit({
name: 'test',
filter: (_, index, { length }) => index === length - 1,
})
expect(fn).toBeCalled().toBeCalledTimes(2)
expect(fn1).toBeCalled().toBeCalledTimes(1)
expect(fn2).toBeCalled().toBeCalledTimes(2)

bus.emit({
name: 'test',
filter: (_, index) => index === 0 || index === 1,
})
expect(fn).toBeCalled().toBeCalledTimes(3)
expect(fn1).toBeCalled().toBeCalledTimes(2)
expect(fn2).toBeCalled().toBeCalledTimes(2)
})
})
14 changes: 14 additions & 0 deletions src/utils/EventBus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ export interface EventBusListenerDescriptor<
name: TListenerName
context?: any
tag?: EventBusListenerTag
filter?: (
callback: EventBusListener,
index: number,
callbacks: EventBusListener[],
) => boolean
}

export type EventBusBeforeOn<TListeners extends EventBusListeners> = {
Expand Down Expand Up @@ -153,10 +158,16 @@ export class EventBus<TListeners extends EventBusListeners> {
name,
context,
tag,
filter,
}: {
name: TListenerName
context?: any
tag?: string | number
filter?: (
callback: EventBusListener,
index: number,
callbacks: EventBusListener[],
) => boolean
} =
typeof eventName === 'object'
? eventName
Expand All @@ -171,6 +182,9 @@ export class EventBus<TListeners extends EventBusListeners> {
tag === callback.__EVENT_BUS_TAG__,
)
}
if (typeof filter === 'function') {
callbacks = callbacks.filter(filter)
}
this.options?.beforeEmit?.[name]?.call(this, context)
return callbacks.map(callback => {
return callback.call(context, ...args)
Expand Down

0 comments on commit 8290e32

Please sign in to comment.