vue-worker
vue-worker copied to clipboard
How to send a message from vue-worker like worker.onmessage
I have that code:
setInterval(() => {
const options = { timeZone: "America/New_York"}, myTime = new Date();
let est_time = myTime.toLocaleString("en-US", options)
let now = new Date(est_time)
let millisTill8 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0) - now;
if (millisTill8 < 0) {
millisTill8 += 86400000; // try after 24 hours tomorrow
}
setTimeout(() => {
this.is_live_chat_active = true
}, millisTill8);
let millisTill20 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 20, 0, 0, 0) - now;
if (millisTill20 < 0) {
millisTill20 += 86400000; // try after 24 hours tomorrow
}
setTimeout(() => {
this.is_live_chat_active = false
}, millisTill20);
}, 86400000);
I want to put it in vue worker. Every day, when the time is 8am or 8pm i want to toggle a boolean variable within a component.
Using just workers that would be possible by:
Worker.onmessage = (toggle) => {
this.toggle_variable = toggle
}
But i can't figure out how to do this using vue-worker
I'd like to know the answer too! This module is pointless to me if I can't communicate back. Perhaps if we pass in a computed field? But I think we send copies, not shared variables, so I don't think we can update computed fields. Can we use Vuex? I'll probably try that.
+1
yeah this module is almost useless if you can't communicate from the Worker during processing.
To be fair, the Web Worker concept is structurally outdated and incompatible with the modern web application development process. I can see why hardly anyone uses it!
If anyone comes across this issue... You actually can just bypass this entire vue-worker
library. However, the implementation below does not inject any vue context. I would recommend just rolling your own... Here is an example that seems to be working fine for me...
myWebWorker.js
const worker = () => {
let i = 0
setInterval(function () {
i++
// Sending data to Main
postMessage(i) // sent data to main app
}, 500)
// Receiving data from Main
onmessage = (event) => {
console.log(`From main> ${event.data}`)
}
}
export const myWebWorker = new Blob([`(${worker.toString()})()`], {
type: 'text/javascript',
})
main.js
import { myWebWorker } from './myWebWorker.js'
if (typeof Worker !== undefined) {
window.URL = window.URL || window.webkitURL // polyfill
// Register the web worker
const worker = new Worker(
window.URL.createObjectURL(myWebWorker),
)
// Receiving data from the Worker
worker.onmessage = function (e) {
console.log(`From worker> ${e.data}`)
}
// Example of sending data from Main to Worker
setTimeout(() => {
worker.postMessage('hello')
}, 5000)
}