user1005240
user1005240

Reputation: 285

How to access object element data from within a web worker?

I am currently learning about web workers and i need to do some computation in the worker that wont hold up the flow in the browser.

Currently I have an ajax call which returns an xml data structure containing multiple data blocks like this:

<data>
   <sub1>
   <sub2>
   <sub3>
</data>
<data>
   <sub1>
   <sub2>
   <sub3>
</data>

I then create an object from this data structure like so:

var node = $(xml).find(data);

I then stringify the object for transfer to the worker like so:

var toPass = JSON.stringify(node);

I then send this variable (toPass) to the worker like so:

worker.postMessage(toPass);

So far all of this works fine, the problem I have is trying to access the data within the worker.

So in the worker i do this:

onmessage = function (oEvent) {

   var node = JSON.parse(oEvent.data);

   for(var  = 0; i < node.length; i++){

               var sub1 = node[i].find('sub1').text();         

   }    

};

The problem I face is trying to access the "sub1", "sub2" & "sub3" data.

I can see that I am trying to access the data incorrectly as I am using an XML.find approach, I feel like I am confusing the data after it has been parsed to a JSON object.

Can anybody show me how to correctly access the data elements within "node[i]"?

Best Regards.

Upvotes: 1

Views: 536

Answers (1)

user1005240
user1005240

Reputation: 285

Ok,

I guess the lesson learned here is never presume anything.

When i done this: var node = $(xml).find('data'); I presumed it returned an array of objects containing all of the sub tags within each tag, however i was wrong, I returned an array (correct in length) but each containing empty objects, this is why I was unable to access the data in the web-worker.

To remedy this, before i send the data require to the worker, i first loop the xml file like so:

var node = $(xml).find('data');

var nodeArray = [];

for (var i=0; i<node.length; i++){  

    var sub1    = $(node[i]).find('sub1').text();
    var sub2    = $(node[i]).find('sub2').text();
    var sub3    = $(node[i]).find('sub3').text();


    var tojsonObj = {'sub1':sub1,'sub2':sub2,'sub3':sub3};

    nodeArray.push(tojsonObj);              
}

worker.postMessage(nodeArray);

This way i do not need to parse anything as the worker can accept arrays (only tested in ff)

To access all this data then within the worker i do this:

onmessage = function (oEvent) {

var nodeArray = oEvent.data;



   for(var i = 0; i < nodeArray.length; i++){

       var sub1     = nodeArray[i].sub1;
       var sub2     = nodeArray[i].sub2;
       var sub3     = nodeArray[i].sub3;

   }

};

Now that I have access to the data, i can do what I like with it inside the loop allowing me to free up some processing time in the browser.

now i just need to process it and figure out how to return it.

Upvotes: 1

Related Questions