Skip to content

Commit

Permalink
feat(EventBus): 支持局部执行
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Sep 25, 2024
1 parent 29e9e21 commit 456905c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/utils/EventBus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,41 @@ describe('EventBus', () => {
expect(f2).toBe('hhh')
expect(f3).toBe(undefined)
})

test('局部执行', () => {
const bus = new EventBus<{
f1: (x: number) => any
f2: (y: string) => any
f3: () => any
}>()

const one = jest.fn()
const offOne = bus.run(_ => {
return _.on('f1', one)
})
bus.emit('f1', 1)
expect(one).toBeCalled().toBeCalledTimes(1)
bus.emit('f1', 2)
expect(one).toBeCalled().toBeCalledTimes(2)
offOne()
expect(one).toBeCalled().toBeCalledTimes(2)

const two = jest.fn()
const three = jest.fn()
const offTT = bus.run(_ => {
return [_.on('f2', two), _.on('f3', three)]
})
bus.emit('f2', '1')
bus.emit('f3')
expect(two).toBeCalled().toBeCalledTimes(1)
expect(three).toBeCalled().toBeCalledTimes(1)
bus.emit('f2', '21')
expect(two).toBeCalled().toBeCalledTimes(2)
expect(three).toBeCalled().toBeCalledTimes(1)
offTT()
bus.emit('f2', '1333')
bus.emit('f3')
expect(two).toBeCalled().toBeCalledTimes(2)
expect(three).toBeCalled().toBeCalledTimes(1)
})
})
19 changes: 19 additions & 0 deletions src/utils/EventBus.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { castArray } from 'lodash-uni'

export type EventBusListenerTag = string | number

export type EventBusListener<
Expand Down Expand Up @@ -230,6 +232,23 @@ export class EventBus<TListeners extends EventBusListeners> {
})
}

/**
* 局部执行。
*
* @param fn 执行函数
* @returns 可以返回一个或多个取消订阅的函数
*/
run(
fn: (bus: this) => void | EventBusOffListener | EventBusOffListener[],
): EventBusOffListener {
const res = fn(this)
return () => {
if (res) {
castArray(res).forEach(off => off())
}
}
}

/**
* 清空事件订阅。
*/
Expand Down

0 comments on commit 456905c

Please sign in to comment.