MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Worker.onmessage

这篇翻译不完整。请帮忙从英语翻译这篇文章

Worker 接口的onmessage属性表示一个EventHandler事件处理函数,当message 事件发生时,该函数被调用。这些事件所属MessageEvent类型,且当Worker子线程返回一条消息时被调用(比如:从DedicatedWorkerGlobalScope.postMessage函数发出的信息)

注意: 消息被装载到 message事件对象的data属性。(译者:即,传递的消息参数将被赋值给onmessage处理函数的事件参数e中的data属性)

语法

myWorker.onmessage = function(e) { ... }

范例

下面的代码片段示范用Worker() 构造函数创建一个Worker对象。当表单的first输入框的值变更时,消息被传递给worker。myWorker.onmessage函数用来处理从worker回传的消息。

var myWorker = new Worker('worker.js');

first.onchange = function() {
  myWorker.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

myWorker.onmessage = function(e) {
  result.textContent = e.data;
  console.log('Message received from worker');
}

worker.js中,  onmessage 函数用来接收从主线程传递过来的信息:

onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}

请注意,主线程中必须以myWorker.onmessage方式调用,  反之worker.js 脚本中, 只需定义 onmessage, 因为worker.js全域有效(DedicatedWorkerGlobalScope).

完整范例,请参考Basic dedicated worker example (run dedicated worker).

规范

规范 状态 注释
WHATWG HTML Living Standard
Worker.onmessage
Living Standard No change from Web Workers.
Web Workers
Worker.onmessage
Editor's Draft Initial definition.

浏览器兼容性

特性 Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
基本支持 4 3.5 10.0 10.6 4
特性 Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
基本支持 4.4 3.5 1.0.1 10.0 11.5 5.1

参阅

Worker 接口所属。

文档标签和贡献者

 此页面的贡献者: spatio
 最后编辑者: spatio,