Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making custom events on webworkers

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?

like image 993
Phillip Ochola Avatar asked Oct 13 '16 13:10

Phillip Ochola


People also ask

How do you write a custom event?

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.

Can Webworkers access DOM?

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.


1 Answers

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.

like image 110
Ramil Kudashev Avatar answered Nov 09 '22 01:11

Ramil Kudashev