Domanda

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.)

È stato utile?

Soluzione

Just do:

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top