javascript - How to pass a global array to web worker and return it? -
last 30-40 minutes i'm trying understand how works passing array web worker , returning it. moment following:
var myglobalarray = [1, 2, 3, 4, 5]; var code = 'self.addeventlistener("message", function(e) {' + ' var receivedarray = e.data.buffer;' + ' var receivedarraysize = receivedarray.length;' + ' //dosomethinwithreceivedarray here...' + ' self.postmessage(receivedarray, [receivedarray]);' + '}, false);'; var blob = new blob([code], {type: 'text/javascript'}); var bloburl = window.url.createobjecturl(blob); var worker = new worker(bloburl); worker.addeventlistener('message', function(e) { var returnedarray = e.data; myglobalarray.length = 0; myglobalarray = e.data.slice(); }, false); var passedarray = new arraybuffer(myglobalarray); worker.postmessage(passedarray, [passedarray]);
but still getting receivedarray undefined
, receivedarray.length undefined
. ideas problem?
a simple example, data json serialised
var blob = new blob(["self.addeventlistener('message', function(e) { postmessage(e.data); }, false);"]), bloburl = window.url.createobjecturl(blob), worker = new worker(bloburl); worker.addeventlistener('message', function (e) { console.log(e.data); }, false); worker.postmessage([1, 2, 3]);
on jsfiddle
or perhaps want, buffer transferred? title/question unclear.
var blob = new blob(["self.addeventlistener('message', function(e) { postmessage(e.data, [e.data]); }, false);"]), bloburl = window.url.createobjecturl(blob), worker = new worker(bloburl), myarray = [1, 2, 3, 4, 5], bufview = new int8array(myarray.length); bufview.set(myarray); worker.addeventlistener('message', function (e) { console.log('transferred buffer in new view:', new int8array(e.data)); }, false); worker.postmessage(bufview.buffer, [bufview.buffer]); console.log('myarray - preserved:', myarray); console.log('bufview - cleared transfer:', bufview);
on jsfiddle
Comments
Post a Comment