Thursday 4 June 2015

Evolution of Javascript from a Web Developer POV

Javascript-Early Stages

In the beginning, there was just plain vanilla JavaScript used for DOM Manipulation and because of the inconsistent DOM APIs across different browsers resulted in lots of bugs.

Javascript Frameworks for DOM Manipulation
 Early frameworks focused on accessing the DOM (the 'query' in jQuery)
Utility functions for animation, cross-browser AJAX, templating added.
jQuery beat out other similar tools such as MooTools, Prototype to become nearly ubiquitous.
There was no "front-end architecture" yet

Javascript Frameworks as UI Widgtes
 Reusable interactive UI components were packaged as UI Widgtes
(ex)jQuery UI, ExtJS, Kendo UI, Bootstrap

Web Application Javascript frameworks
 Mature JavaScript Frameworks designed for building MVC/MVVM web applications
 Usually include templating, AJAX CRUD, and  1 way/2 way model binding
 (ex)Knockout, Backbone.js, AngularJS, Batman.js, Ember.js


JavaScript Tools

DOM Abstraction
  • Prototype
  • YUI
  • jQuery
  • Mootools
  • ExtJS
  • Script.aculo.us
  • Dojo
MV? Frameworks
  • Ember
  • Angular
  • Backbone
  • Spine
  • CanJS
Utility Libraries
  • Clementine
  • Underscore
  • Knockout
  • Socket.io
  • RequireJS
  • Lodash
Testing Tools
  • Mocha
  • QUnit
  • Jasmine
  • JSHint
  • CSSLint
  • Chai
  • ExpectJS
  • PhantomJS
Templating
  • Handlebars
  • Mustache
  • EJS
  • HAML
  • Dust
Mobile UI Frameworks
  • jQuery Mobile
  • SenchaTouch
  • KendoUI
UI Component Libraries
  • jQuery UI
  • Bootstrap
  • Ratchet
Pseudo Languages
  • Coffeescript
  • Typescript
  • Dart
Build Tools
  • Grunt
  • Yeoman
Package Managers
  • NPM
  • Bower
Preprocessors / Mixin Libraries
  • SASS
  • LESS
  • Bourbon
  • Preboot
None of the Above!
  • Node.js

Friday 22 May 2015

Angular 2 -How to make Ajax call with Custom Service



I have been playing with Angular 2 to make ajax calls.But the Angular Quick-start does not have any documentation for $http module used as of Angular 1x. After googling , found out the answer, that Angular 2.0 DOES NOT have a $http service

1.Angluar JS has a separate data persistence layer, that will cover HTTP. This is not finished yet.
2.Because of Zone in Angular 2 you can use any existing mechanism for fetching data. This includes XMLHttpRequest fetch() and any other third party libraries.
3.XHR in the compiler is meant to be private, and should not be used.
 So the solution will be,
Create a factory class which acts as a wrapper and hold all the methods for HTTP requests.
  export const $http = {
	get: function(url: string) {
		return _sendRequest(url, null, 'GET');
    },
    post: function(url: string, payload: any){
    	return _sendRequest(url, payload, 'POST');
    },
    put: function(url: string, payload: any){
    	return _sendRequest(url, payload, 'PUT');
    },
    delete: function(url: string, payload: any){
    	return _sendRequest(url, null, 'DELETE');
    }
}
Use XMLHttpRequest for making the actual Ajax calls and return a Angular Promise.
    function _sendRequest(url: string, payLoad: any, type: string): Promise {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open(type, url);
            req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

            if (payLoad) {
                req.send(JSON.stringify(payLoad));
            } else {
                req.send(null);
            }
        });
    }
Handle the JSON parsing in the "resolve" callback and error handling in the "reject" callback.
    function _sendRequest(url: string, payLoad: any, type: string): Promise {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open(type, url);
            req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

            req.onload = function() {
                if (req.status == 200) {
                    resolve(JSON.parse(req.response));
                } else {
                    reject(JSON.parse(req.response));
                }
            };

            req.onerror = function() {
                reject(JSON.parse(req.response));
            };

            if (payLoad) {
                req.send(JSON.stringify(payLoad));
            } else {
                req.send(null);
            }
        });
    }
Register a "then" callback for the Promise returned and set the view objects for rendering them to the template
   $http.get('http://jsonplaceholder.typicode.com/posts?userId=1').then(function(json) {
         appClass.greetings = json;
      });

Example plunkr




Tuesday 19 May 2015

AngularJS 2.0 - What's new? My Take

Before u Start:

Read the following to get insight on specifications over which the AngularJS 2.0 is built.

1.Angular JS is written in ES6. Simple explanation of ES6 features can be read from here.
2.Angular JS uses AtScript(@ script) - Angular's Extension of ES6 features to support annotations & decorators similar to annotations in Java.
3.Angular JS uses traceur transpiler. It allows the new and proposed future EcmaScript features to be used in browsers.
4.es6-shim.js - To add ES6 in current browsers. 

Annotations:

AtScript provides 3 types of annotations - Type Annotations, Field Annotations and MetaData Annotations.
Lets start for now with, 

             1.@Component - Indicates the class is a component
             2.@View- As the name suggests-it is the view of the component.It can be a HTML template.They add some meta data to the class in order to give it a specific meaning. They are a declarative way to add meta data to code.

How to create a Angular 2.0 Component?

Angular 2 works with a concept of components. Each component consist of 2 parts
  1. The Annotation Section(@Component & @View) – This consist of the meta data (component selector, template) for that component
  2. The Component Controller Section(Class) – This is a ES6 Class, from which the template would be reading the properties that are interpolated ({{…}}) inside it .

   import {  ComponentAnnotation as Component,
  ViewAnnotation as View,bootstrap} from 'angular2/angular2';

  @Component({
  selector: 'app'
  })
  @View({
    template: 'Hello {{ name }}'
   })
  class App{
    constructor() {
     this.name = 'Muthu!';
    }
  }
   bootstrap(App);
Example plunkr

Saturday 31 January 2015

Display Loading image on Partial Page Refresh/Ajax

Continuing from my previous post on displaying the loading symbol on page load, this post I will explain how we can do the same for Partial Page refresh (aka) Ajax.

Add a hidden div 

Add a loading image inside a hidden div somewhere in your page.

<div id="loader" style="display:none">
          <img src="your/image/path/loading.gif" alt="loading..."/>
</div>


Add loading image to Body thro' JavaScript

Add the loading image to body tag using jquery.

$('body').prepend('<div id="loading-image" style="page-loader"/>');
$('#loading-image').html($('#loader').html());


Add CSS for page-loader

.page-loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
 }


Add loading image with page mask

If you wish to mask the entire page on displaying the loading image, add the loading image within a div that will acts as page mask and then add that div to the 'body' tag.

$('body').prepend('<div class="pagemask"><div id="loading-image" style="page-loader"/></div>');
$('#loading-image').html($('#loader').html());


add the CSS for page mask 

.page-loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background:#fff;
  z-index: 9999;
 }
மகிழ்ச்சியான குறிமுறையாக்கம் !

Saturday 3 January 2015

Display Loading Image on Page Load

Of late, Websites are more media intensive. There are tons of JavaScript written to make pages look stunning and visually impressive.But the evil side is that it takes toll on the page loading times.

So what do I do , when i don't want to sacrifice my rich UI for page loading times.Alternative is to display a loading image masking the entire body until the DOM is loaded. 

How to get this running?

Get a loader image

We can get loading image GIF's on google search.Pick up the most suitable one and make sure it is open source to use.

Add a Div

Add a div like below immediately after the body tag.This is necessary as we want the whole page to be masked.

<div class="page-loader"></div>
Add CSS for page-loader
.page-loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url(your/image/path/loading.png) 50% 50% no-repeat #ede9df;
}
With this the entire body is masked and covered by the loading image.The Z index make sure loader is on top of all the DOM elements

Add JavaScript Code

In my case , I opted for jQuery as my JS framework.Add the below piece of code 
$(window).load(function() {
 $(".page-loader").fadeOut("slow");
})
window.load ensures the entire DOM is loaded and then fades out the loading image.