I made a webworker and tried to add a custom event called progress as follows:
self.updateProgress = function(no){
let event = new CustomEvent(
'progress',
{
detail : {
description: "event from webworker to update progress",
timeofevent: new Date(),
eventcode: 15
},
bubbles: true,
cancelable: false,
data : no
});
self.console.log(self.dispatchEvent(event));
};
On the parent JavaScript:
scope.worker.addEventListener('progress', (e) => { //cannot add custom events to worker yet
scope.progress = e.data;
});
The problem is that the event is never triggered, and from what I have read, it seems that message and error are the only events that are attached to the worker object. Is it impossible to add custom events?
A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.
Web workers can't access DOM elements from the web page. Web workers can't access global variables and JavaScript functions from the web page. Web workers can't call alert() or confirm() functions. Objects such as window, document and parent can't be accessed inside the web worker.
You set worker.addEventListener('message', (e) => {})
in main thread, but you don't self.dispatchEvent
at worker. Instead, you call self.postMessage(obj, []);
and worker implementation does the job (passing data between threads and firing events).
Proto of WebWorker
is EventTarget
in Chrome, so you probably could use it as event target where you create it. But worker
in main thread and self
in worker are not the same object / scope, so you dispatch event and listen event on different targets.
But nothing prevents you from using standard self.postMessage
way for keeping track of loading progress.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With