Hacker News new | ask | show | jobs
by TweedHeads 6172 days ago
Why web workers can't take a function or an object?

  myobject={
    start:      function(){ /* do stuff */ }
    stop:       function(){ /* end worker */ }
    postMessage:function(){ /* communicate */ }
    onmessage:  function(){ /* receiving data*/ }
    onerror:    function(){ /* handle stuff */ }  
  }
  
  myworker = new Worker(myobject);
  myworker.start();
  myworker.postMessage("dostuff");
  myworker.stop();
Or something like that...
2 comments

That can't work because the individual methods may contain a closure to a non-threadable object (like the DOM). The reason why all of the logic is forced into in an external script is to prevent contention from occurring - your proposed solution definitely would not allow for that.

On the other hand, allowing for an easy way to call global functions of the child worker would be really nice.

   var worker = new Worker("worker.js");
   worker.start();
Child Worker:

   start = function(){
     // Gets called by the parent
   };
That would be sexy and surely simplify a lot of logic surrounding message passing.
Point taken, then let me rephrase that.

Threads we can fire and forget. Threads we can start "inside" our script and let them work while we do other stuff.

  myfunnyfunc = function(){/* do long funny stuff */}
  mycallback  = function(){/* do something when done */}
  
  mythread = new Thread(myfunnyfunc,mycallback);
Asynchronous like xmlhttprequest, just a way to replace the "settimeout" hack.
Taking a lok at it, sending messages back and forth is retarded. Just call the damn functions by their names with their arguments since the worker itself is already threaded and sandboxed.