Wednesday, February 12, 2014

Threading to JavaScript 3



The second post of this article series shows small application with web worker. This post going to shows web worker with JSON. Please refer first post and second post.

Following shows main page HTML structure. Main page has three buttons with respective onclick event handler. One button for send JSON data to the web worker, another button for get JSON data from web worker and third button for terminate web worker from JSON message.

Web worker demo

Following shows main page JavaScript code. First part of this code contain implementation for start web worker and it contain with onmessage event listener for web worker object. After that it has implementation of onclick event handler in each buttons. Inside those methods create JSON object to send web worker. 

Following shows doWebWorker.js file implementation. Inside the switch statement check JSON object. For Get request create new JSON object and send back to the main page.

var message;
that = this;
self.addEventListener('message', function (e) { 
 
 var data = e.data;
 switch (data.cmd) {
  case 'send':
   that.sendMessage('WORKER RECEIVED JSON DATA: ' + data.msg);
   break;
  case 'get':
   var val = {
    'cmd': 'WORKER SEND JSON DATA',
    'msg': 'worker said hi !'
   }
   that.sendMessage(val);
   break;
  default:
   that.sendMessage('WORKER STOPPED: ' + data.msg);
   // Terminates the worker.
   that.terminatesWorker();
 };
}, false);

function sendMessage(message)
{
 self.postMessage(message);
}

function terminatesWorker() {
 self.close();
}

Final result looks like shown in below.


Result of Send Json button click

Result of Get Json button click

Result of Stop Worker button click

No comments :

Post a Comment