本文介绍了Javascript网络工作者:为什么我需要postMessage两次来触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Javascript和网络编程的新手。我想找出网络工作者,并有以下代码(在chrome中运行):

I am a newcomer to Javascript and web programming in general. I am trying to figure out web workers, and have the following code (running in chrome):

worker_example.html

worker_example.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="worker_example.js"></script>
    </head>
<html>

worker_example.js

worker_example.js

var worker = new Worker("worker.js");

worker.addEventListener('message', function(e) {
    document.write("hello");
}, false);

worker.postMessage("");

worker.js

worker.js

// self.postMessage("");

我的问题是为什么不 worker.postMessage()触发事件?但是,如果我取消注释worker.js中的单行,一切正常。

My question is why doesn't worker.postMessage("") trigger the event? If I uncomment the single line in worker.js, however, everything works fine.

推荐答案

附加到<$ c的事件监听器$ c> worker 侦听工作人员父页面的消息。您还需要在worker 中注册一个监听器

The event listener attached to worker listens for messages coming from the worker to the parent page. You need to register a listener in the worker as well.

parent.js

parent.js

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

worker.addEventListener('message', function (e) {
  console.log(e.data);
});

worker.postMessage('marco');

worker.js

worker.js

self.addEventListener('message', function (e) {
  self.postMessage(e.data + ' polo');
});

这篇关于Javascript网络工作者:为什么我需要postMessage两次来触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:44