【问题标题】:Passing jQuery reference through Web Worker通过 Web Worker 传递 jQuery 引用
【发布时间】:2016-06-28 18:32:01
【问题描述】:

我正在将一些 url 轮询请求卸载给网络工作者。为此,我需要从调用的 DOM 元素中获取某些属性,将它们传递到 url 请求中,然后使用结果更新原始 DOM 元素。由于多个 DOM 元素使用此函数来获取更新,因此我需要通过 $(this) 或等效的唯一标识符来确保更新正确的元素。

我从"Passing objects to a web worker""Can I pass a jQuery object to a web worker" 等问题中了解到这是不可能的,因此我正在寻找一种方法来效仿。

这是我的代码的粗略轮廓:

//main.js
function update(){
    var data = { 'id'     : $(this).attr('itemid'),
                 'filter' : $(this).attr('filter')}
    updatePoller.postMessage(data);
}

//worker.js
this.onmessage = function(e){
    //format params from e.data
    //make GET request to url
    //when done...
    postMessage(req.responseText);
}

//main.js (again)
updatePoller.onmessage = function(message){
    //process response
    //update child elements of $(this)
}

如您所见,我不需要在 Web Worker 中访问 $(this),但在请求返回后我需要引用以更新正确的元素。有什么方法可以通过 web worker 传递对 DOM 元素的唯一引用?

【问题讨论】:

    标签: jquery dom web-worker


    【解决方案1】:

    当您无法使用元素引用时,唯一标识元素的常用方法是使用id。或者,您可以使用 data-* 属性,但实际上 ids 是为此特定目的而创建的。

    所以(见 cmets):

    //main.js
    var lastId = 0;
    function update(){
        // Assign ID if necessary
        if (!this.id) {
            ++lastId;
            this.id = "__auto" + lastId;
        }
        var data = { 'id'       : $(this).attr('itemid'),
                     'filter'   : $(this).attr('filter'),
                     'elementId': this.id}
        updatePoller.postMessage(data);
    }
    
    //main.js (again)
    updatePoller.onmessage = function(message){
        // Use the `element` value sent back to look it up by ID:
        $("#" + message.data.elementId).xyz();
    }
    

    如果让所有这些自动全局变量(因为 id 值会创建自动全局变量)困扰您,您可以在完成后删除 ID:

    //main.js (again)
    updatePoller.onmessage = function(message){
        var elm = $("#" + message.data.elementId);
        if (elm.attr("id").startsWith("__auto")) {  // auto ID?
            elm.attr("id", "");                     // remove it
        }
        elm.xyz();
    }
    

    或使用更少的 jQuery:

    //main.js (again)
    updatePoller.onmessage = function(message){
        var elm = $("#" + message.data.elementId)[0];
        if (elm && elm.id.startsWith("__auto")) {
            elm.id = "";
        }
        $(elm).xyz();
    }
    

    【讨论】:

    • 谢谢,我设法将$(this)id 传递给worker,然后从worker 返回一个JSON 对象,其中包含响应和元素ID
    猜你喜欢
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 2013-09-10
    • 2014-12-02
    • 2020-04-01
    • 1970-01-01
    • 2011-06-28
    相关资源
    最近更新 更多