Skip to content

Commit

Permalink
feat(useWebWoker): return worker (#507)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
wheatjs and antfu committed May 13, 2021
1 parent 87a464d commit c5cf03a
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions packages/core/useWebWorker/index.ts
@@ -1,6 +1,6 @@
/* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */

import { ref, Ref } from 'vue-demi'
import { ref, Ref, shallowRef } from 'vue-demi'
import { tryOnUnmounted } from '@vueuse/shared'
import { ConfigurableWindow, defaultWindow } from '../_configurable'

Expand All @@ -22,38 +22,40 @@ export function useWebWorker(
} = options

const data: Ref<any> = ref(null)
let worker: Worker
const worker = shallowRef<Worker>()

const post: typeof worker.postMessage = function post(val: any) {
if (!worker)
const post: typeof Worker.prototype['postMessage'] = function post(val: any) {
if (!worker.value)
return

worker.postMessage(val)
worker.value.postMessage(val)
}

const terminate: typeof worker.terminate = function terminate() {
if (!worker)
const terminate: typeof Worker.prototype['terminate'] = function terminate() {
if (!worker.value)
return

worker.terminate()
worker.value.terminate()
}

if (window) {
// @ts-expect-error untyped
worker = new window.Worker(url, workerOptions)
worker.value = new window.Worker(url, workerOptions)

worker.onmessage = (e: MessageEvent) => {
worker.value!.onmessage = (e: MessageEvent) => {
data.value = e.data
}

tryOnUnmounted(() => {
worker.terminate()
if (worker.value)
worker.value.terminate()
})
}

return {
data,
post,
terminate,
worker,
}
}

0 comments on commit c5cf03a

Please sign in to comment.