这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions client/src/event-bus/bus.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import EventBus from './bus'

describe('EventBus (class)', () => {
it('should subscribe event', () => {
const eventBus = EventBus.getInstance()

let result = null
const unsubscribe = eventBus.on('subscribe-test', () => (result = 'success'))
eventBus.emit('subscribe-test')

expect(result).toBe('success')

unsubscribe()
})

it('should unsubscribe event', () => {
const eventBus = EventBus.getInstance()

let result = null
const unsubscribe = eventBus.on('subscribe-test', () => (result = 'success'))
unsubscribe()
eventBus.emit('subscribe-test')

expect(result).toBe(null)

unsubscribe()
})

it('should subscribe once', () => {
const eventBus = EventBus.getInstance()

let result = null
eventBus.once('subscribe-test', (flag: string) => (result = flag))
eventBus.emit('subscribe-test', 'success')
eventBus.emit('subscribe-test', 'fail')

expect(result).toBe('success')
})
})
63 changes: 63 additions & 0 deletions client/src/event-bus/bus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
type Key = string
type Handler = (...payload: any[]) => void
type UnsubscribeFunc = () => void

interface Bus {
on(key: Key, handler: Handler): UnsubscribeFunc
off(key: Key, handler: Handler): void
emit(key: Key, ...payload: Parameters<Handler>): void
once(key: Key, handler: Handler): void
}

export default class EventBus implements Bus {
#record: Map<Key, Handler[]>
static #instance: EventBus

constructor() {
this.#record = new Map()
}

get record() {
return this.#record
}

public static getInstance() {
if (!this.#instance) {
this.#instance = new EventBus()
}

return this.#instance
}

public on(key: Key, handler: Handler) {
if (!this.#record.has(key)) {
this.#record.set(key, [])
}

const queue = this.#record.get(key)
queue?.push(handler)

return () => {
this.off(key, handler)
}
}

public off(key: Key, handler: Handler) {
const index = this.#record.get(key)?.indexOf(handler) ?? -1
this.#record.get(key)?.splice(index >>> 0, 1)
}

public emit(key: Key, ...payload: any[]) {
const handlers = this.#record.get(key)
handlers?.forEach((handler) => handler(...payload))
}

public once(key: Key, handler: Handler) {
const handleOnce = (...payload: any[]) => {
handler(...payload)
this.off(key, handleOnce)
}

this.on(key, handleOnce)
}
}
1 change: 1 addition & 0 deletions client/src/event-bus/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as EventBus } from './bus'