javascript - What interface do I need to implement to allow object to be passed through WebWorker's postMessage? -


webworkers api in javascript allows pass objects between worker's thread , main thread using worker.postmessage in browser , postmessage in worker.

i've been playing around, , not postmessage passed arrays , objects regexp instances, assume there's interface these objects implement. example string conversion, implement .tostring method:

"" + {tostring: function() {return "hello world!"}}; //prints `hello world!` 

similarly, can implement tojson method:

json.stringify({tojson: alert}); //throws `typeerror: 'alert' called on object not implement interface window.` //  - demonstrating tojson being called 

my question is, should implement postmessage player class pass through communication channel:

function player(name) {   this.name = name; } player.prototype = object.create(eventemitter2.prototype); 

i intentionally added inheritance part here - need object remain instance of something, not data holder. regexp, need reconstructed through method or methods define - must fail if required context (type definitions, such eventemitter2) not defined in new scope.

alas, can't. can't specify own serialiser/deserialiser (or marshaller/unmarshaller). can retain object structures though, in cases enough, information constructors , functions won't pass through.

here's how know this:

the part of specification in charge of web worker's postmessage (which same window's postmessage, way) can found here: https://html.spec.whatwg.org/multipage/comms.html#dom-messageport-postmessage

it's lot of uninteresting technical stuff, important part this:

let message clone result of obtaining structured clone of message argument, [...]

the structured clone algorithm here: https://html.spec.whatwg.org/multipage/infrastructure.html#structured-clone

as can see, things pretty grim. checks built-in objects , values (like number or blob), , construct them accordingly. can pass arbitrary objects, structure remain.


so, can do?

  1. accept it. data goes through, json more limited. that's not bad actually, , encourages separation of transport layer , implementation.
  2. implement marshaller/unmarshaller of own, wrap postmessage , likes. that's not terribly difficult actually, , can nice exercise.
  3. weep bitter tears. option, helps deal day-to-day life.

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -