gpt4 book ai didi

javascript - this._waiting 未定义

转载 作者:行者123 更新时间:2023-11-28 02:19:47 27 4
gpt4 key购买 nike

我正在尝试为网络 worker 编写一个简单的包装类。当其中一条已定义的消息发送到 WebWorker 时,LayoutBridge 会分配一个票证,该票证会在处理请求时返回。这样,我应该能够为这些请求运行回调。

我收到以下错误

TypeError: this._waiting is undefined

在_recvMsg中。

这是代码,我几天来一直在尝试解决这个自制的谜题,但看不出我做错了什么,因为等待是在 LayoutBridge 构造函数中定义的,并且(只是为了确保)在 init 函数中。

我会在这之后立即发布一个 jsfiddle,但也许有人已经知道答案了。

var LayoutBridge = function(){

this._waiting = {};
this._initialized = false;

};

LayoutBridge.prototype.init = function(opts){
if(!this._initialized){
this._waiting = {};

this._worker = new Worker('/layout-worker.js');
this._worker.onmessage = this._recvMsg;
var ticket = _.uniqueId();

var waitingCallback = function(){
this._initiated = true;
};
waitingCallback.bind(this);
this._waiting[ticket] = waitingCallback;

this._worker.postMessage({cmd: 'init', ticket: ticket});
this._initialized = true;
}
};

LayoutBridge.prototype.addVertex = function(callback){
if(!this._initialized) throw "Initialize LayoutBridge first";

var ticket = _.uniqueId();
this._waiting[ticket] = callback;
this._worker.postMessage({cmd: 'addVertex', ticket: ticket});
};

LayoutBridge.prototype.removeVertex = function(id, callback){
if(!this._initialized) throw "Initialize LayoutBridge first";

var ticket = _.uniqueId();
this._waiting[ticket] = callback;
this._worker.postMessage({cmd: 'removeVertex', id: id, ticket: ticket});
};

LayoutBridge.prototype.addEdge = function(sourceId, targetId, callback){
if(!this._initialized) throw "Initialize LayoutBridge first";

var ticket = _.uniqueId();
this._waiting[ticket] = callback;
this._worker.postMessage({cmd: 'addEdge', sourceId: sourceId, targetId: targetId});
};

LayoutBridge.prototype._recvMsg = function(e){
this._waiting[e.data.ticket](e.data.payload);
//delete this._waiting[e.data.ticket];
};

编辑,这是 fiddle :建议包括:http://jsfiddle.net/MGSvj/2/

最佳答案

将函数分配给另一个类会更改其范围。

在这里,您将 this._recvMsg 函数分配给 Worker 类。

this._worker.onmessage = this._recvMsg;

因此,在此处的代码中,this 将是窗口对象或工作对象(不太确定,但它肯定不会是 LayoutBridge 对象)。

LayoutBridge.prototype._recvMsg = function(e){
this._waiting[e.data.ticket](e.data.payload);
//delete this._waiting[e.data.ticket];
};

要解决此问题,您所需要做的就是

var oThis = this;
this._worker.onmessage = function (){ oThis._recvMsg };

此外,根据https://developer.mozilla.org/en/docs/DOM/Blob

Blob 需要一个数组作为参数。

所以你的代码

var blob = new Blob($('#layout-worker').html());

应该是

var blob = new Blob([$('#layout-worker').html()]);

关于javascript - this._waiting 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849674/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com