我想爲web工作者編寫一個簡單的包裝類。當其中一個定義的消息發送給webworker時,LayoutBridge會分配一個票據,該票據在處理請求時返回。這樣,我應該可以爲這些請求運行回調。this._waiting is undefined
我收到以下錯誤
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];
};
編輯,這裏的小提琴:包括建議:http://jsfiddle.net/MGSvj/2/
謝謝,擺脫了錯誤的。你有調查網絡工作者的一般建議嗎? (我知道這個特定的錯誤不會被我所能做的很多)也許你有一些普遍的智慧... – lowerkey 2013-04-06 10:35:13
鉻提供了一個很好的調試工具。只需輸入'debugger;'在你得到錯誤的代碼中。在運行你的代碼時,保持chrome控制檯打開(按F12)。而且你的代碼將停在那裏,你可以很容易地找出一步一步出錯的地方。 – 2013-04-06 10:40:09
好吧,它擺脫了錯誤,但回調仍然沒有被調用。我使用了'var oThis = this; this._worker.onmessage = function(e){oThis._recvMsg(e); };' – lowerkey 2013-04-06 10:40:44