Skip to content

Commit

Permalink
feat: add once function in emitter
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Sep 11, 2020
1 parent cafbad6 commit 6a21d24
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/use/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,21 @@ export function useEmitter() {
})
}

function once(type, handler) {
const handleOn = () => {
handler && handler()
off(type, handleOn)
}
on(type, handleOn)
}

return {
on,
broadcast,
dispatch,
off,
emit
emit,
once
}
}

Expand Down
21 changes: 20 additions & 1 deletion test/unit/tests/use/emitter.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEmitter } from '../../../../src/use/new-emitter'
import { useEmitter } from '../../../../src/use/emitter'
import { mount } from '@vue/test-utils'
import { onMounted } from 'vue'

Expand Down Expand Up @@ -161,4 +161,23 @@ describe('useEmitter', () => {

expect(handleEmit).toBeCalledTimes(2)
})

it('once ', () => {
const handleEmit = jest.fn()
const Comp = {
template: '<div></div>',
setup() {
const { once, emit } = useEmitter()

once('emit', handleEmit)

emit('emit', 1)
emit('emit', 2)
}
}

mount(Comp)

expect(handleEmit).toBeCalledTimes(1)
})
})

0 comments on commit 6a21d24

Please sign in to comment.