Home > Mobile >  Call worker via postmessage from a class
Call worker via postmessage from a class

Time:01-15

I am currently learning how to handle with workers. I made a very simple example with a class. All js files are in the src folder.

//***********index.html**************
<!DOCTYPE html>
  <html>
    
    <head>
      <title>test</title>
      <meta charset="UTF-8"/>
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
    </head>
        
    <body>
        
      <script type="module" src="./src/main.js"></script>

    </body>
  </html>
//***********main.js**************
import {test} from "./test.js";
new test.DataLoader();
//***********test.js***************
export const test = (() => {

class DataLoader{
  constructor(){
    
    this.worker = new Worker('./src/worker.js', {type: 'module'});
    
    this.worker.onmessage = (e) => {        
      this.result = e.data;
      console.log(this.result);
    };
    
  }//end constructor
}//end class


return {DataLoader};
})();
//***********worker.js***************

postMessage("kimba");

But if I want to trigger the worker via postMessage, it doesn't work. I'm sure it's not a big thing but i just don't see the error.

//***********test.js***************
export const test = (() => {

class DataLoader{
  constructor(){
    
    this.worker = new Worker('./src/worker.js', {type: 'module'});
    
    this.worker.onmessage = (e) => {        
      this.result = e.data;
      console.log(this.result);
    };
    
    //this is new, call postMessage method
    this.postMessage("kimba");
    
  }//end constructor

  //this is new, a postMessage method
  postMessage(msg){
    this.worker.postMessage(msg);
  }

}//end class


return {DataLoader};
})();
//***********worker.js***************

self.onmessage = (msg) => {
  self.postMessage(msg);    
};

Exactly as above, but this time the worker should not respond immediately when it is created, but should wait for a postMessage from DataLoader. Of course, I would like to use this in a more complex environment, but posting 1000 lines here is clumsy. This simple example sums up my problem. I want to call the worker with postmessage from within DataLoader.

CodePudding user response:

The tip with the self got me thinking. msg.data instead of msg alone in the worker.js and it works. Your tip with the self gave me the feeling that maybe one more prefix or postfix is ​​missing. I messed around with it for hours earlier and it wouldn't want to run and your tip put me on the right track. Thank you.

self.onmessage = (msg) => {
  self.postMessage(msg.data);    
};
  • Related