Nig*_*iri 6 javascript html5 web-worker
当我创建像以下这样的网络工作者时......
var w = new Worker("./Scripts/sample.js");
Run Code Online (Sandbox Code Playgroud)
sample.js想要来自调用者的一些参数!!
可能?
Bub*_*les 13
我没有使用网络工作者一大堆,但根据这个描述,我相信你可以按照这些方式做到:
var worker = new Worker("sample.js");
worker.postMessage({ "args": [ ] });
Run Code Online (Sandbox Code Playgroud)
然后,在sample.js中,按照以下行构造它:
self.addEventListener("message", function(e) {
var args = e.data.args;
// do whatever you need with the arguments
}, false);
Run Code Online (Sandbox Code Playgroud)
这与传统的参数传递并不完全相同,因为postMessage中的任何内容都必须是可格式化为JSON(例如,没有函数).但是,有一个很好的机会可以做你需要它做的事情.
将 sample.js 用作像这样工作的网络时,如何传递参数var w = new Worker("./Scripts/sample.js");?
您可以在查询字符串中传递参数,并在 sample.js 中从 location.search. 您不需要调用 postMessage 来完成此操作。
调用代码将是
var w = new Worker("./Scripts/sample.js?answer=42&question=ultimate");
Run Code Online (Sandbox Code Playgroud)
这将呼叫工人。在 sample.jslocation.search中将等于?answer=42&question=ultimate. 我们可以用下面的代码优雅的拉出来
var parameters = {}
location.search.slice(1).split("&").forEach( function(key_value) { var kv = key_value.split("="); parameters[kv[0]] = kv[1]; })
var question = parameters['question'];
var answer = parameters['answer'];
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到一个活生生的例子
如果您有大量数据要发送,请不要使用查询字符串。