1

我正在尝试为网络工作者编写一个简单的包装类。当定义的消息之一发送到 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/

4

1 回答 1

1

将你的函数分配给另一个类会改变它的范围。

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

this._worker.onmessage = this._recvMsg;

因此,在此处的代码中,将是窗口对象或工作对象(不太确定,但绝对不会是 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()]);
于 2013-04-06T10:29:43.490 回答