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?
- accept it. data goes through, json more limited. that's not bad actually, , encourages separation of transport layer , implementation.
- implement marshaller/unmarshaller of own, wrap
postmessage
, likes. that's not terribly difficult actually, , can nice exercise. - weep bitter tears. option, helps deal day-to-day life.
Comments
Post a Comment