Skip to content

Commit

Permalink
feat: deactivate alongside keep-alive
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Sep 5, 2020
1 parent 93eac48 commit 995ccf0
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
36 changes: 36 additions & 0 deletions __tests__/KeepAlive.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { GlobalEventsImpl as GlobalEvents } from '../src/GlobalEvents'
import { mount } from '@vue/test-utils'
import { defineComponent, KeepAlive, nextTick } from 'vue'

const TestWrapper = (name: string, fn: Function) =>
defineComponent({
template: `
<keep-alive>
<GlobalEvents :${name}="fn" v-if="active" />
</keep-alive>
`,

components: { KeepAlive, GlobalEvents },
data: () => ({ active: true }),
methods: { fn },
})

describe('GlobalEvents with KeepAlive', () => {
test('skips events when deactivated', async () => {
const onKeydown = jest.fn()
const wrapper = mount(TestWrapper('onKeydown', onKeydown))

wrapper.vm.active = false
await nextTick()

document.dispatchEvent(new Event('keydown'))
expect(onKeydown).not.toHaveBeenCalled()

wrapper.vm.active = true
await nextTick()

expect(onKeydown).not.toHaveBeenCalled()
document.dispatchEvent(new Event('keydown'))
expect(onKeydown).toHaveBeenCalledTimes(1)
})
})
15 changes: 14 additions & 1 deletion src/GlobalEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import {
VNodeProps,
onMounted,
onBeforeUnmount,
ref,
onActivated,
onDeactivated,
} from 'vue'
import { isIE } from './isIE'

Expand Down Expand Up @@ -67,6 +70,14 @@ export const GlobalEventsImpl = defineComponent({
[EventListener[], string, Options | undefined | boolean]
> = Object.create(null)

const isActive = ref(true)
onActivated(() => {
isActive.value = true
})
onDeactivated(() => {
isActive.value = false
})

onMounted(() => {
Object.keys(attrs)
.filter((name) => name.startsWith('on'))
Expand All @@ -91,7 +102,9 @@ export const GlobalEventsImpl = defineComponent({

const handlers: EventListener[] = listeners.map(
(listener) => (event) => {
props.filter(event, listener, eventName) && listener(event)
isActive.value &&
props.filter(event, listener, eventName) &&
listener(event)
}
)

Expand Down

0 comments on commit 995ccf0

Please sign in to comment.