dom - Passing jQuery reference through Web Worker -


i'm working on offloading url polling requests web worker. this, need fetch attributes dom element of invokation, pass them url request, update original dom element results. since multiple dom elements use function fetch updates, need pass through $(this) or equivalent unique identifier ensure correct element updated.

i understand questions such "passing objects web worker" , "can pass jquery object web worker" not possible, looking means emulate this.

here rough outline of code:

//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 e.data     //make request url     //when done...     postmessage(req.responsetext); }  //main.js (again) updatepoller.onmessage = function(message){     //process response     //update child elements of $(this) } 

as can see, don't need access $(this) inside web worker, need reference once request has returned in order update correct element. there ways pass unique reference dom element through web worker?

the usual way uniquely identify element when can't use reference use id. alternately, use data-* attribute, ids made specific purpose.

so (see comments):

//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 `element` value sent id:     $("#" + message.data.elementid).xyz(); } 

if having of automatic globals (since id values create automatic globals) bothers you, remove id when done it:

//main.js (again) updatepoller.onmessage = function(message){     var elm = $("#" + message.data.elementid);     if (elm.attr("id").startswith("__auto")) {  // auto id?         elm.attr("id", "");                     // remove     }     elm.xyz(); } 

or less jquery:

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

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -