我正在尝试为网络工作者编写一个简单的包装类。当定义的消息之一发送到 webworker 时,LayoutBridge 会分配一张票,该票在处理请求时返回。这样,我应该能够为这些请求运行回调。
我收到以下错误
类型错误:this._waiting 未定义
在 _recvMsg 中。
这是代码,几天来我一直在尝试解决这个自制的谜语,但看不到我做错了什么,因为在 LayoutBridge 构造函数和(只是为了确保)中都定义了等待在初始化函数中。
我会在此之后立即发布一个 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];
};
编辑,这里是小提琴:建议包括:http: //jsfiddle.net/MGSvj/2/