Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, October 27, 2015

Unit Testing with Karma and Mocha


JavaScript becomes a big hero in these days. If you think about the few years back developers use it only for the client side scripting. But now the time has changed the game. Nowadays JavaScript is really powerful and can use for developing server side functions too. Because of this growth in development in JavaScript, it opens up many paths to thinks to the developer when to do the development. Unit testing is one of the major component of the development process with the rise of the TDD approach. The as much as you do unit testing you can make an assurance about the small pieces of the business logic works as according to expectation. 
As I said in earlier with the growth of the capabilities in the  JavaScript, arise a requirement of the applying TDD approach for the client – side as well. To achieve this TDD approach in client – side developer have to work with a set of tools. In this post aim is to start to write a first unit test in JavaScript. The set of tools going to use for this mention in below.
1). Test Runner – Karma
2). Test Framework – Mocha
3). Test Assertion Tool – Chai
My Folder structure in project,
project/
src/
test/
node_modules/
Inside src folder contain all business logic JavaScript files and test folder contains the unit test JavaScript files. Nodejs module contain in node_modules folder. Using npm init command create package.json file.
Following command line installs karma, mocha, chai assertion library, mocha and chai adapter for the karma at once.
npm install karma mocha chai karma-mocha karma-chai --save-dev

In here we installed karma locally. Benefit of it use we can use different karma version in different projects. But when we start to work with karma, we have to go to bin folder of the karma local installation. So this is bring additional effort to the developer. Run following command to avoid this situation. Before do this needs to uninstall the globally install karma version.

npm install –g karma-cli

Now run below command and create karma configurations.

karma init

After you provide successful answers to the questions ask by the karma configuration process you get the file as in below.
// Karma configuration

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],


    // list of files / patterns to load in the browser
    files: [
      'src/**/*.js',
      'test/**/*.spec.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR ||   
    // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  })
}

In here we installed karma locally. The benefit of it is we can use different karma version in different projects. But when we start to work with karma, we have to go to the bin folder of the karma local installation. So this brings additional effort to the developer. Run the following command to avoid this situation. Before do this needs to uninstall the global install karma version.

Now im going to write my first unit test in “test.spec.js” file as in below.
describe("A test suite", function() {
    
    var num1 = 0;
    
   beforeEach(function() { 
         num1 += 10  
   });
   
   afterEach(function() { 
           
   });
   
   it('should fail', function() {
        expect(num1).to.equal(11);
         });
});

In this test, I created a variable call “num1” and adding the 10 for it each time before test gets to run. The “beforeEach” function runs before all the unit test and “afterEach” function get run after each unit test. In here I use mocha as test framework and chai for assertions for the write unit test. The expect style assertion give the capability to write unit tests in BDD way.

Now start to run unit tests by enter following command as “karma start”. Then you see chrome browser and unit test start to run. Following images shows the result of the unit test run.





Now you have written your first unit test and run it. Until the next post, Happy Coding Winking smile

Wednesday, October 21, 2015

Nodejs with Visual Studio

 

Nodejs is a mostly use platform among the web developers in nowadays. When im looking into nodejs I wanted a good tool to write the application. First I started it with using VS Code. But when I was using it I didn’t get that rich user experience like in Visual Studio. Yeah.. I know VS Code still growing and its not a substitution for the Visual Studio. So I start look into the way to develop the Nodejs web application with Visual Studio. Yeah I found it. There is Nodejs tools for visual studio. So I downloaded it from here. This tool is still growing. After you download it and  install go to new project creation in visual studio. Then you can see like below.

image

So I created blank nodejs project using visual studio. It shows like in below.

image

You can see node project created with all the basic dependencies and basic functions. Press F5 and see how it works.

image

It open up browser and shows the respond return from express. Visual Studio provide complete debugging support to develop nodejs applications.

image

And also VS give you intellisense support and Interactive window to code and see the immediate result, NPM package manager support to manage packages in application, source control integration, cloud integration and typescript support.

image

So this is just a start and introduction of creating a nodejs application with Visual Studio using its rich set of features. So in next post ill talk about developing simple nodejs application.  Until then have fun with this tool.

Tuesday, March 17, 2015

Angular Style Guide by John Papa

 

AngularJs is a MVC framework use by front-end. This is getting popular among developers for front-end developers because of it rich set of capabilities. Normally when we do the development in back-end development almost every time we are trying to use the best practices and gaudiness as a discipline of the developers. So I thought about the same way about the angular. I looked around the web for that kind of guidelines and best practices for AngularJs. That time I found the set of guidelines given by john papa. I don’t say we should follow of them. Based on the scenario, application and our requirement we can use it for front-end development. So im going to share that link with you guys.

Here we go : https://github.com/johnpapa/angular-styleguide#naming

Happy Coding Folks.

Wednesday, September 3, 2014

Mobile Apps: Develop once and Run in all platforms

All most every mobile developer would like to reach large audience with all platforms. But the blocker for that approach is each time they want to develop the app again. So it take effort and time. In this kind of a scenario c# developers can use Xamarin and Apache Cordova. In earlier post  I described how to use Nomad visual studio extension to develop mobile app for the apache cordova. In this post going to describe about Microsoft developed visual studio extension for cross-platform mobile applications using HTML, CSS, and JavaScript.

First of all Download and install the extension on Visual Studio 2013 Pro Update 3. This extention gives all the set of tools need for development.


After you set-up the development environment, can create new project as shown in below.


After you create a new project, can change the target development platform going properties of the project. Under properties go to configuration manager window and change it as shown in following image. And also you need to change the Platform under project properties as well.


This VS extension also contain one main page as same like Nomad VS extension which is index html page. And also this project template create with configuration file. You can configure application level settings, specify HTTP uri that can access by application and Apache Cordova capabilities.
And this extension include Apache Cordova intellisense support for common Cordova plugins using both JavaScript and TypeScript.

And one of other main feature I saw in this extension compare with Nomad extension is debugging capability. In Nomad extension you don't get this capability unless you use browser developer tools. At that it was headache for me because of compare with time.

With Nomad VS extension we got only ripple emulator for application simulation purposes. But with this extension you get three options to test your app. First one is you can use ripple as usual. Second native emulators and third option is device. With my experience of developing cross platform mobile application I always choose the device for app simulation purposes. Because most of the time whatever we see in the simulator getting change when we deploy it into device.

So these are the basic details of this new Multi-Device Hybrid app development VS extension. I think this post will help you get start on with this new tool. 

Wednesday, August 13, 2014

SPA with AngularJs

 

AngularJS is a JavaScript frame work which use to create dynamic web applications. Its runs with plain JavaScript and HTML, so you don’t need use any other things when you are creating a web applications. You can read and learn more about the AngularJs from this link. In this post going to explain about the steps needs to follow when creating a SPA (Single Page Application) with AngualrJS.

Open your visual studio and create an empty web application. Install AngularJS core and router files using NuGet. After that create a folder called “app”. In this folder going to hold the old AngularJS related scripts files. Inside of this folder create a file calle “app.js”. In this JavaScript file is going to initialize all configurations when angular start up. Folder structure would be like as shown in below.

app

---------controller

--------------main.js

--------------submain.js

---------app.js

views

---------main

------------main.html

index.html

inside app folder contain the controller folder. It hold two angular controllers such as main and submain. And there is views folder for keep all the views. There is another subfolder call “main” to hold the views belongs to main controller. Index view is the initial view start in the application. In app.js file place the following code snippets.

var app = angular.module('spaapp', ['spaapp.controllers', 'ngRoute']);

var appctrl = angular.module('spaapp.controllers', []);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider
      .when("/",
      {
          templateUrl: "views/main/main.html",
          controller: "main"
      })
      .when("/sub",
      {
          templateUrl: "views/main/submain.html",
          controller: "submain"
      })
      .otherwise({
          redirectTo: '/'
      });

    $locationProvider.html5Mode(true);
}]);
In here main module create as “spaapp”. Its getting inject with “ngRoute” and “spaapp.controllers”. The “ngRoute” use for client side routing inside the application and “spaapp.controllers” use as module of the controllers in the application. after that shows routing configuration of the application. When user navigate to root url, route configuration load the main controller with main.html view. As the same way it does for the “/sub” path.
So lets create content of the index.html view. 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <base href="/" />
</head>
<body ng-app="spaapp">

  <ng-view></ng-view>

    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-route.min.js"></script>
    <script src="app/app.js"></script>
    <script src="app/controller/main.js"></script>
    <script src="app/controller/submain.js"></script>
</body>
</html>
Now what we left to do is creation of the main and submain controllers.
main controller
appctrl.controller('main', ['$scope', function ($scope) {
    $scope.message = 'main';
}]);
In main controller use the controller module created earlier in app.js file. This controller inject with $scope for handle the model. In this controller bind message to the $scope property called “message”. Following shows the main.html view for the above controller. This view contain route for the sub controller.
main.html view
<p>The controller name is {{message}}!</p>

<a href="/sub"> Sub Controller </a>
submain controller 
appctrl.controller('submain', ['$scope', function ($scope) {
    $scope.message = 'sub main';
}]);

The submain controller is doing same thing as the main controller. In below showing a submain.html view. This view also same likes the main.html view. It has a link to navigate to the main view.

sub main view
<p>The controller name is {{message}}!</p>

<a href="/"> Back to Main Controller </a>

In this SPA, we load to views dynamically to the index.html. This magic happens through “<ng-view>” tag in the index.html. main and submain views get append to the “<ng-view>” tag when it called through the router. Route configuration handle the controller and view according to the route. Now run the application.
Main View
1_thumb[3]

Sub Main View, you can see url of the browser.

2_thumb[1]

So we created SPA using an AngularJs. Give a try on this.

Happy Coding wlEmoticon-smile[2]

Saturday, April 26, 2014

PhoneGap App : Google Map MarkerClusterer

In last post I was described how to get current location and show it as marker in the map. Let's think a scenario which is you have to show lot of markers in the map. In this case map going to be the fill with markers and user can't get an idea on looking at the map. This going to be loose the user experience. So solution for this kind of a requirement is group the markers in the map. There are various approaches for achieve the solution for this. Today I'm going to explain one method belongs to Clustering which is MarkerClusterer. Clustering  is simplifies your data visualization by consolidating data that are nearby each other on the map in an aggregate form.

The MarkerClusterer is a client side library. This use grid-based clustering to a collection of markers. It works by iterating though the markers in the collection that you wish to cluster and adding each one into the closest cluster if it is within in a minimum square pixel bounds. For demo this approach I used the previous post implementation as basement. Actually this is a extending the previous post implementation.

To develop marker clusterer in your application first you have to reference it in your HTML page. You can download the markerclusterer.js from here. Other than there is no any changes in the HTML page from the previous post.

<!DOCTYPE html> <html> <head> <title>Map View</title> <link href="style/jquery.mobile-1.4.2.css" rel="stylesheet" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <div data-role="page" id="map-page" data-url="map-page"> <div data-role="header"> <span style="align-content:center;">Map</span> </div> <div data-role="content" data-position="fixed" id="map_canvas"> <!-- map loads here... --> </div> <div data-role="footer"> Footer </div> </div> <!--Jquery--> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <!--Jquery Mobile--> <script type="text/javascript" src="scripts/jquery.mobile-1.4.2.js"></script> <!--Cordova--> <script type="text/javascript" src="scripts/cordova.js"></script> <!--Google Map--> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&amp;sensor=true&amp"></script> <!--Google Map Marker Cluster--> <script type="text/javascript" src="scripts/markerclusterer.js"></script> <!--Map View--> <script type="text/javascript" src="scripts/JS/MapView.js"></script> <script type="text/javascript"> $(document).ready( function () { var mapView = new PhoneGapMapApp.MapView(); mapView.init(); } ); </script> </body> </html>
In MapView.js added new methods for create collection of locations, load themarkers to the map, initiate and create the clusterer in the map. After fire devereday event belongs to cordova create the location collection. after the start to create the marker belongs to relevant location in the collection. after create marker collection form locations initiate and create the cluster view in the map. You can see the implementation in below code.

PhoneGapMapApp = {} PhoneGapMapApp.MapView = function () { this._map = null; this._currentLocation = null; this._locations = null; this._markerClusterer = null; } PhoneGapMapApp.MapView.prototype = { init: function () { this._defaultLocation = new google.maps.LatLng(6.5006036, 80.2711642); this._attachEventHandlers(); }, /** * Attach event handlers. */ _attachEventHandlers: function () { document.addEventListener("deviceready", this._onDeviceReady(this), false); }, /** * device APIs are available. */ _onDeviceReady: function (obj) { console.log('device ready'); obj._getRealContentHeight(); obj._loadMap(); obj._identifyCurrentLocation(); obj._loadLocationData(); obj._loadMapMarkers(); }, /** * Setup the content hieght. */ _getRealContentHeight: function () { var header = $.mobile.activePage.find("div[data-role='header']:visible"); var footer = $.mobile.activePage.find("div[data-role='footer']:visible"); var content = $.mobile.activePage.find("div[data-role='content']:visible:visible"); var viewport_height = $(window).height(); var content_height = viewport_height - header.outerHeight() - footer.outerHeight(); if ((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) { content_height -= (content.outerHeight() - content.height()); } $('#map_canvas').height(content_height); }, /** * create map. */ _loadMap: function () { var myOptions = { zoom: 4, center: this._defaultLocation, mapTypeId: google.maps.MapTypeId.ROADMAP }; this._map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); }, /** * Identify current location. */ _identifyCurrentLocation: function () { if (navigator.geolocation) { browserSupportFlag = true; var that = this; var currentPositionCallback = function (position) { that._identifyCurrentLocationCompleted(position); }; var noGeolocationCallback = function () { that._handleNoGeolocation(browserSupportFlag); }; navigator.geolocation.getCurrentPosition( currentPositionCallback, noGeolocationCallback, { 'enableHighAccuracy': true, 'timeout': 20000 }); } else { browserSupportFlag = false; this._handleNoGeolocation(browserSupportFlag); } }, /** * Handles the situation when current location not found * or not allow from the user for access current location. */ _handleNoGeolocation: function (errorFlag) { this.goTo(this._defaultLocation); }, /** * Current location identify operation success callback. */ _identifyCurrentLocationCompleted: function (position) { this._currentLocation = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); this.goTo(this._currentLocation); }, /** * Show current location in the map. */ goTo: function (position) { this._setMarkerForLocation(position); this._map.setCenter(position); }, /** * Set marker for location. */ _setMarkerForLocation: function (latLng) { var marker = new google.maps.Marker({ position: latLng, map: this._map, title: "You are here !!!" }); }, /** * Load markers for the map. */ _loadMapMarkers: function () { if (this._locations != null) { this._displayParksListInMap(); } }, /** * Create marker list from location details. */ _displayParksListInMap: function () { var markers = []; for (var locationIndex = 0; locationIndex < this._locations.length; locationIndex++) { var location = this._locations[locationIndex]; var marker = null; //Add new location to the markers var latLng = new google.maps.LatLng ( location.LocationLatitude, location.LocationLongitude ) marker = new google.maps.Marker ({ position: latLng, title: location.LocationName }); markers.push(marker); } this._initializeMarkerClusterer(markers); }, /** * Initialize marker cluster view in the map. */ _initializeMarkerClusterer: function (markers) { this._markerClusterer = new MarkerClusterer( this._map, markers, { maxZoom: 18, gridSize: 15 }); }, /** * Create local static data. */ _loadLocationData: function () { var location = {}; var locations = new Array(); location = { LocationID: 01, LocationName: 'Asiri Surgical Hospital', LocationLongitude: 79.880167, LocationLatitude: 6.894737 }; locations.push(location); location = { LocationID: 02, LocationName: 'The Asiri Central Hospital', LocationLongitude: 79.8658391, LocationLatitude: 6.9205805 }; locations.push(location); location = { LocationID: 03, LocationName: 'Majestic City', LocationLongitude: 79.8547562, LocationLatitude: 6.8940211 }; locations.push(location); location = { LocationID: 04, LocationName: 'Liberty Plaza', LocationLongitude: 79.8515386, LocationLatitude: 6.911252 }; locations.push(location); this._locations = locations; } }

Friday, April 4, 2014

Show current location of the PhoneGap map app

In last post I was described the way to develop PhoneGap map app using google map API v3. In this post Im going to show you how to get the user current location and show it on the map as marker. For this approach I use same code I wrote for the previous post. In below showing the implementation I did to achieve this task.

PhoneGapMapApp = {} PhoneGapMapApp.MapView = function () { this._map = null; this._currentLocation = null; } PhoneGapMapApp.MapView.prototype = { init: function () { this._defaultLocation = new google.maps.LatLng(6.5006036, 80.2711642); this._attachEventHandlers(); }, /** * Attach event handlers. */ _attachEventHandlers: function () { document.addEventListener("deviceready", this._onDeviceReady(this), false); }, /** * device APIs are available. */ _onDeviceReady: function (obj) { console.log('device ready'); obj._getRealContentHeight(); obj._loadMap(); obj._identifyCurrentLocation(); }, /** * Setup the content hieght. */ _getRealContentHeight: function () { var header = $.mobile.activePage.find("div[data-role='header']:visible"); var footer = $.mobile.activePage.find("div[data-role='footer']:visible"); var content = $.mobile.activePage.find("div[data-role='content']:visible:visible"); var viewport_height = $(window).height(); var content_height = viewport_height - header.outerHeight() - footer.outerHeight(); if ((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) { content_height -= (content.outerHeight() - content.height()); } $('#map_canvas').height(content_height); }, /** * create map. */ _loadMap: function () { var myOptions = { zoom: 4, center: this._defaultLocation, mapTypeId: google.maps.MapTypeId.ROADMAP }; this._map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); }, /** * Identify current location. */ _identifyCurrentLocation: function () { if (navigator.geolocation) { browserSupportFlag = true; var that = this; var currentPositionCallback = function (position) { that._identifyCurrentLocationCompleted(position); }; var noGeolocationCallback = function () { that._handleNoGeolocation(browserSupportFlag); }; navigator.geolocation.getCurrentPosition( currentPositionCallback, noGeolocationCallback, { 'enableHighAccuracy': true, 'timeout': 20000 }); } else { browserSupportFlag = false; this._handleNoGeolocation(browserSupportFlag); } }, /** * Handles the situation when current location not found * or not allow from the user for access current location. */ _handleNoGeolocation: function (errorFlag) { this.goTo(this._defaultLocation); }, /** * Current location identify operation success callback. */ _identifyCurrentLocationCompleted: function (position) { this._currentLocation = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); this.goTo(this._currentLocation); }, /** * Show current location in the map. */ goTo: function (position) { this._setMarkerForLocation(position); this._map.setCenter(position); }, /** * Set marker for location. */ _setMarkerForLocation: function (latLng) { var marker = new google.maps.Marker({ position: latLng, map: this._map, title: "Greetings!" }); }, }
The _identifyCurrentLocation method called by after create the map object. In this method has success callback and failure callback. In _setMarkerForLocation method set marker for the current location. If current location not found then app will shows the default location.

Wednesday, March 26, 2014

Google map with PhoneGap app

In previous post I was described the PhoneGap development with visual studio using Nomad extension. Today I'm going to make post about create a app using a google map. Here I'm using google map API v3 for do operation with map. following shows html page of the app.

<!DOCTYPE html> <html> <head> <title>Map View</title> <link href="style/jquery.mobile-1.4.2.css" rel="stylesheet" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <div data-role="page" id="map-page" data-url="map-page"> <div data-role="header"> Map </div> <div data-role="content" data-position="fixed" id="map_canvas"> <!-- map loads here... --> </div> <div data-role="footer"> Page footer </div> </div> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="scripts/jquery.mobile-1.4.2.js"></script> <script type="text/javascript" src="scripts/cordova.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&amp;sensor=true&amp"></script> <script type="text/javascript" src="scripts/JS/MapView.js"></script> <script type="text/javascript"> $(document).ready( function () { var mapView = new PhoneGapMapApp.MapView(); mapView.init(); } ); </script> </body> </html>

Im using here Jquery Mobile and wrote JavaScript class called MapView.js which is using custom object pattern. Page contain with mainly 3 parts such as header, content and footer. Content div use to create the map. Following show the MapView.js which is include the basic operations for the map.

PhoneGapMapApp = {} PhoneGapMapApp.MapView = function () { this._map = null; } PhoneGapMapApp.MapView.prototype = { init: function () { this._defaultLocation = new google.maps.LatLng(6.5006036, 80.2711642); this._attachEventHandlers(); }, /** * Attach event handlers. */ _attachEventHandlers: function () { document.addEventListener("deviceready", this._onDeviceReady(this), false); }, /** * device APIs are available. */ _onDeviceReady: function (obj) { console.log('device ready'); obj._getRealContentHeight(); obj._loadMap(); }, /** * Setup the content hieght. */ _getRealContentHeight: function () { var header = $.mobile.activePage.find("div[data-role='header']:visible"); var footer = $.mobile.activePage.find("div[data-role='footer']:visible"); var content = $.mobile.activePage.find("div[data-role='content']:visible:visible"); var viewport_height = $(window).height(); var content_height = viewport_height - header.outerHeight() - footer.outerHeight(); if ((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) { content_height -= (content.outerHeight() - content.height()); } $('#map_canvas').height(content_height); }, /** * create map. */ _loadMap: function () { var myOptions = { zoom: 4, center: this._defaultLocation, mapTypeId: google.maps.MapTypeId.ROADMAP }; this._map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); // Add an overlay to the map of current lat/lng var marker = new google.maps.Marker({ position: this._defaultLocation, map: this._map, title: "Greetings!" }); } }
To load the map here I'm using DeviceReady event belong to cordova. This event fire when phonegap fully loaded. The _getRealContentHeight method setup the height for the shows the map in the page. The _loadMap method create the map object and set the marker for already know location. In following image show the result of all this effort. 






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

Wednesday, January 15, 2014

Threading to JavaScript 2

The previous post explained about basics of web worker. In this post going to describe a small application created using web worker. In this demo shows add two numbers using web worker. Following HTML shows two inputs.

Web worker demo

Add numbers
Following JavaScript code reside in main page. This code start web worker and attach with event handlers.


JavaScript code snippet of doWebWorker.js,
var message;
that = this;
self.addEventListener('message', function (e) { 
 
 var sum = parseInt(e.data[0]) + parseInt(e.data[1]);
 var workerResult = 'Result: ' + sum;
 that.sendMessage(workerResult);
}, false);

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

Following image shows the end result.


Tuesday, December 17, 2013

Threading to JavaScript 1

JavaScript is a single-threaded environment. Simply if you wants run multiple scripts at the same time you cant achieve that requirement with JavaScript. Think about the scenario in a web site you wants to retrieve data through AJAX, needs to do manipulation in UI and DOM at the same time. But you can do this because of script execution happens within a single thread. So in currently what you do normally achieve this kind of goal. You use techniques like setTimeout(), setInterval(), XMLHttpRequest, and event handlers. But in HTML5 gives to you better option than these workarounds. That is Web Worker.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. perfect for keeping your UI refresh, performant, and responsive for users. There are two types of web workers, Dedicated Workers and Shared Workers. In this article discuss about Dedicated web worker.

Let's do small demo about web worker. Create HTML content like below with two buttons. Those two buttons bind with 'onClick' event.

Web worker demo

Create script like below with two onClick events. First of all check whether browser support web worker. After check Worker object create or not. If it not create new object. If the web worker file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. The worker will not begin until the file has completely downloaded and executed. If file not exists returns an 404, the worker will fail silently. Communication between a work and its parent page is done using an event model and the postMessage() method.


Following script shows the content of doWebWorker.js file. In this javascript file capture message from main page send data back to main page. And also worker terminate operation contain in this separate script file.
var message;
that = this;
self.addEventListener('message', function (e) {  
 //basic demo
 message = e.data;
 that.sendMessage(message);
}, false);

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

When click Start Worker button send message to the web worker and eventlistener of web worker catch it send back to the main page. When click Stop Worker button terminate web worker.