Skip to content

Commit

Permalink
feat(@tinacms/events): EventBus#subscribe can accept an array of even…
Browse files Browse the repository at this point in the history
…t names
  • Loading branch information
ncphillips committed Sep 17, 2020
1 parent 371b891 commit 63ef4db
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
16 changes: 12 additions & 4 deletions packages/@tinacms/core/src/event.ts
Expand Up @@ -25,13 +25,21 @@ export interface CMSEvent {
export class EventBus {
private listeners = new Set<Listener>()

subscribe = (event: string, callback: Callback): (() => void) => {
const listener = new Listener(event, callback)
subscribe = (event: string | string[], callback: Callback): (() => void) => {
let events: string[]

this.listeners.add(listener)
if (typeof event === 'string') {
events = [event]
} else {
events = event
}

const newListeners = events.map(event => new Listener(event, callback))

newListeners.forEach(newListener => this.listeners.add(newListener))

return () => {
this.listeners.delete(listener)
newListeners.forEach(listener => this.listeners.delete(listener))
}
}

Expand Down
13 changes: 13 additions & 0 deletions packages/@tinacms/core/src/events.test.ts
Expand Up @@ -29,6 +29,19 @@ describe('EventBus', () => {

expect(listener).toHaveBeenCalledWith(event)
})
test('for an array of eventscalls listeners and passes it the dispatched event', () => {
const listener = jest.fn()
const events = new EventBus()
const one = { type: 'one' }
const two = { type: 'two' }

events.subscribe(['one', 'two'], listener)
events.dispatch(one)
events.dispatch(two)

expect(listener).toHaveBeenCalledWith(two)
expect(listener).toHaveBeenCalledWith(one)
})
describe('after calling unsubscribe', () => {
it('does not invoke the listener', () => {
const listener = jest.fn()
Expand Down

0 comments on commit 63ef4db

Please sign in to comment.