From c6f23465761b03693f397095b700eed58221a5e2 Mon Sep 17 00:00:00 2001 From: Oliver Bell Date: Tue, 14 Jun 2022 16:27:08 +0100 Subject: [PATCH] fix(web-worker): ensure event listener functions are bound correctly (#1487) --- packages/web-worker/src/pure.ts | 4 ++-- test/web-worker/src/eventListenerWorker.ts | 3 +++ test/web-worker/test/init.test.ts | 7 +++++++ 3 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 test/web-worker/src/eventListenerWorker.ts diff --git a/packages/web-worker/src/pure.ts b/packages/web-worker/src/pure.ts index d9404868c977..41979135248c 100644 --- a/packages/web-worker/src/pure.ts +++ b/packages/web-worker/src/pure.ts @@ -102,8 +102,8 @@ export function defineWebWorker() { this.inside.emit(event.type, event) return true }, - addEventListener: this.inside.on, - removeEventListener: this.inside.off, + addEventListener: this.inside.on.bind(this.inside), + removeEventListener: this.inside.off.bind(this.inside), postMessage: (data) => { this.outside.emit('message', { data }) }, diff --git a/test/web-worker/src/eventListenerWorker.ts b/test/web-worker/src/eventListenerWorker.ts new file mode 100644 index 000000000000..8fb8afde725a --- /dev/null +++ b/test/web-worker/src/eventListenerWorker.ts @@ -0,0 +1,3 @@ +self.addEventListener('message', (e) => { + self.postMessage(`${e.data} world`) +}) diff --git a/test/web-worker/test/init.test.ts b/test/web-worker/test/init.test.ts index 389728f3bc93..d58f7872674a 100644 --- a/test/web-worker/test/init.test.ts +++ b/test/web-worker/test/init.test.ts @@ -1,6 +1,7 @@ import { expect, it } from 'vitest' import MyWorker from '../src/worker?worker' +import MyEventListenerWorker from '../src/eventListenerWorker?worker' const testWorker = (worker: Worker) => { return new Promise((resolve) => { @@ -23,6 +24,12 @@ it('simple worker', async () => { await testWorker(new MyWorker()) }) +it('event listener worker', async () => { + expect.assertions(1) + + await testWorker(new MyEventListenerWorker()) +}) + it('can test workers several times', async () => { expect.assertions(1)