Question

I create a web worker as follows:

export class WorkerApi {

    private worker:Worker;

    constructor() {
        this.worker = new Worker("web-worker.js");
        this.worker.onmessage = this.messageHandler;
    }

    private messageHandler (e) {

        // need "this" for the instantiated WorkerApi object here

        // ...
    }

The problem I have is when messageHandler is called, this is the Worker object. I need access to my WorkerApi object. How do I get that? (I'm using TypeScript but I believe this is a JavaScript question.)

Was it helpful?

Solution

Just do:

this.worker.onmessage = this.messageHandler.bind(this);

The this value within the handler will point to your WorkerApi instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top