Skip to content

Commit

Permalink
feat: emitter support multi-parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Sep 14, 2020
1 parent 1c3c861 commit 382f431
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
18 changes: 9 additions & 9 deletions src/use/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ export function useEmitter() {
const { value, type, emitComponentInstance } = e
if (type === BROADCAST) {
if (isChildComponent(currentComponentInstance, emitComponentInstance)) {
handler && handler(value)
handler && handler(...value)
}
} else if (type === DISPATCH) {
if (isChildComponent(emitComponentInstance, currentComponentInstance)) {
handler && handler(value)
handler && handler(...value)
}
} else {
handler && handler(value)
handler && handler(...value)
}
}

Expand All @@ -32,29 +32,29 @@ export function useEmitter() {
emitter.on(type, handleWrapper)
}

function broadcast(type, evt) {
function broadcast(type, ...args) {
emitter.emit(type, {
type: BROADCAST,
emitComponentInstance: currentComponentInstance,
value: evt
value: args
})
}

function dispatch(type, evt) {
function dispatch(type, ...args) {
emitter.emit(type, {
type: DISPATCH,
emitComponentInstance: currentComponentInstance,
value: evt
value: args
})
}

function off(type, handler) {
emitter.off(type, handler[wrapper])
}

function emit(type, evt) {
function emit(type, ...args) {
emitter.emit(type, {
value: evt
value: args
})
}

Expand Down
13 changes: 7 additions & 6 deletions test/unit/tests/use/emitter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ describe('useEmitter', () => {
setup() {
const { broadcast } = useEmitter()
onMounted(() => {
broadcast('foo', 1)
broadcast('foo', 1, 2)
})
}
}
mount(Comp)

expect(handleFoo).toBeCalledWith(1)
expect(handleFoo).toBeCalledWith(1, 2)
})

it('当使用 broadcast 时,如果 a 组件不是 b 组件的子组件的话,那么不会触发事件', () => {
Expand Down Expand Up @@ -64,7 +64,7 @@ describe('useEmitter', () => {
template: '<div></div>',
setup() {
const { dispatch } = useEmitter()
dispatch('foo', 1)
dispatch('foo', 1, 2)
}
}
const Comp = {
Expand All @@ -79,7 +79,7 @@ describe('useEmitter', () => {
}
mount(Comp)

expect(handleFoo).toBeCalledWith(1)
expect(handleFoo).toBeCalledWith(1, 2)
})

it('当使用 dispatch 时,如果 a 组件不是 b 组件的父组件的话,那么不会触发事件', () => {
Expand Down Expand Up @@ -152,14 +152,15 @@ describe('useEmitter', () => {

on('emit', handleEmit)

emit('emit', 1)
emit('emit', 1, 2)
emit('emit', { test: 'emit' })
}
}

mount(Comp)

expect(handleEmit).toBeCalledTimes(2)
expect(handleEmit).toHaveBeenNthCalledWith(1, 1, 2)
expect(handleEmit).toHaveBeenNthCalledWith(2, { test: 'emit' })
})

it('once ', () => {
Expand Down

0 comments on commit 382f431

Please sign in to comment.