无法在'Window'上执行'postMessage':需要2个参数,但只有1个参数

时间:2017-03-05 21:18:30

标签: javascript html5 web worker

我目前有一名网络工作者试图接受1个参数

wworker = postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);
wworker.addEventListener('message', findDistance);

但是,控制台上会出现错误:“未捕获的TypeError:无法在'Window'上执行'postMessage':需要2个参数,但只有1个存在。” AFAIK postMessage第二个参数是可选的。

这是我的worker.js

var distance;

function findDistance(event) {
var destinationLat, destinationLon, originLat, originLon, haversineLat, haversineLon, thetaLat, thetaLon;
destinationLat = event.data[0] * (Math.PI/180);
destinationLon = event.data[1] * (Math.PI/180);
originLat = event.data[2] * (Math.PI/180);
originLon = event.data[3] * (Math.PI/180);
thetaLat = destinationLat - originLat;
thetaLon = destinationLon - originLon;
haversineLat = (1-Math.cos(thetaLat))/2;
haversineLon = (1-Math.cos(thetaLon))/2;
distance = 2 * 6376 * Math.asin(Math.sqrt(haversineLat + Math.cos(originLat) * Math.cos(destinationLat) * haversineLon));
postMessage(distance);
}

self.addEventListener('message', findDistance);

1 个答案:

答案 0 :(得分:2)

您没有在.postMessage()上致电Worker;你也在message循环的每次迭代中附加一个新的for事件。将wworker.addEventListener('message', findDistance);移到for循环之外,在wworker.postMessage()循环中调用for

var wworker = new Worker("assets/scripts/webworker.js");
wworker.addEventListener('message', findDistance);

for(i=0;i<lines.length;i++){
    var temp = lines[i].split(",");     

    wworker.postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);

    textCoords.shift();
    textCoords.shift();
}