padolsey / operative

:dog2: Seamlessly create Web Workers
MIT License
655 stars 45 forks source link

remove _marshal and _demarshal functions #12

Closed calvinmetcalf closed 11 years ago

calvinmetcalf commented 11 years ago

postMessage serializes naturally via structured cloning which is a better algorithm than JSON.stringify as it can handle circular dependencies

padolsey commented 11 years ago

We use structured cloning if it's available. By default the _marshal and _demarshal methods are just pass-throughs:

// ... L147
    _marshal: function(v) {
        return v;
    },
    _demarshal: function(v) {
        return v;
    },

We only use JSON methods if we get a 'pingback:objectTransferSupport=NO' from the worker (src):

// ... L272
    if (data === 'pingback:objectTransferSupport=NO') {
        this._marshal = function(o) { return JSON.stringify(o); };
        this._demarshal = function(o) { return JSON.parse(o); };
    }

This is misleading though (a mistake of mine during development), it should in-fact be called 'pingback:structuredCloningSupport=NO' -- I'll make sure to change that soon.

To detect support for structured-cloning we send a message postMessage(['PING']) and if the worker receives it as an Array then we know it supports structured-cloning, otherwise the worker receives it as a string "PING". And in that case we serialize/deserialize JSON from that point onwards.

calvinmetcalf commented 11 years ago

Are there browsers that support workers but not structured cloning or is this for use in the the fallbacks?

padolsey commented 11 years ago

This is only as a fallback. AFAICT Safari 4 supports Worker, but not Blob/BlobBuilder, and only allows strings to be passed via postMessage -- so this fallback is used there.

calvinmetcalf commented 11 years ago

Are you able to test it that far back, Sauce labs only goes back to Safari 5 (workers but no window.URL)

padolsey commented 11 years ago

Not sure how reliable this is but I tested using version 4 from here http://michelf.ca/projects/multi-safari/

Right now operative doesn't work in Sf4 for other reasons which I'm now looking into.

calvinmetcalf commented 11 years ago

ah well this can be closed, I was going through the code trying to figure out if the transferable objects issue needed to be that they should be added to the code or the documentation.

padolsey commented 11 years ago

Fixed naming confusion here https://github.com/padolsey/operative/commit/9033a06aaa8acc35f251f620c04f04096c13978e