Reputation: 32884
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.)
Upvotes: 0
Views: 98
Reputation: 43718
Just do:
this.worker.onmessage = this.messageHandler.bind(this);
The this
value within the handler will point to your WorkerApi
instance.
Upvotes: 1