this._waiting未定义

时间:2013-04-06 10:20:20

标签: javascript web-worker

我正在尝试为Web worker编写一个简单的包装器类。当其中一个已定义的消息发送给webworker时,LayoutBridge将分配一个票证,该票据在处理请求时返回。这样,我应该可以为这些请求运行回调。

我收到以下错误

  

TypeError:this._waiting未定义

在_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/

1 个答案:

答案 0 :(得分:1)

将您的功能分配给另一个类会改变其范围。

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

this._worker.onmessage = this._recvMsg;

因此在这里的代码中,这个将是window对象或worker对象(对它不太确定,但它肯定不会是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()]);