Versionsvergleich
Aus ProgrammingWiki
Vergleich: 2018-03-10T22:45:20+00:00 → 2018-03-10T22:45:20+00:00
<language>Javascript</language> | |
<run id="5aa45bbd790s9"> | |
function InlineWorker(func, self) { | |
var _this = this; | |
var functionBody; | |
var ticket = 0; | |
self = self || {}; | |
functionBody = func.toString().trim().match( | |
/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/ | |
)[1]; | |
return new Worker(URL.createObjectURL( | |
new Blob([ functionBody ], { type: "text/javascript" }) | |
)); | |
function postMessage(data) { | |
setTimeout(function() { | |
_this.onmessage({ data: data }); | |
}, 0); | |
} | |
this.self = self; | |
this.self.postMessage = postMessage; | |
setTimeout(func.bind(self, self), 0); | |
} | |
InlineWorker.prototype.postMessage = function postMessage(data) { | |
var _this = this; | |
setTimeout(function() { | |
_this.self.onmessage({ data: data }); | |
}, 0); | |
}; | |
var JSONParseWorker = new InlineWorker(function(self) { | |
self.onmessage = function(e) { | |
var data = e.data; | |
var json = JSON.parse( data ); | |
postMessage(json); | |
}; | |
}); | |
JSONParseWorker.onmessage = function(e) { | |
if(JSONParseWorker.callbacks[e.data.id]){ | |
JSONParseWorker.callbacks[e.data.id](e.data.data); | |
delete JSONParseWorker.callbacks[e.data.id]; | |
} | |
}; | |
JSONParseWorker.callbacks = []; | |
JSONParseWorker.parse = function(json, callback){ | |
function uuidv4() { | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { | |
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); | |
return v.toString(16); | |
}); | |
} | |
var id = uuidv4(); | |
JSONParseWorker.callbacks[id] = callback; | |
JSONParseWorker.postMessage('{"id":"'+id+'", "data":'+json+'}'); | |
}; | |
JSONParseWorker.parse('{"name":"test"}',function(e){alert(e);}) | |
</run> |