Monday, 25 March 2013

Website start-up terms

How to start a website :
1. choose a registrar company, buy a domain name.
2. choose a web- host company, they will provide some server space and web interfaces to your website.
3.go back to your registrar and provide your server space address.By doing this you told your resistrar that whose DNS server you are using.






Now when website hit first time, my request will propagate to the root servers, those root servers do know  who knows where all the .com mappings taken, and finally you get your response, thats what registrar do for you.


MX- mail server setup. go to google.com, reach at appropriate choice that I want to host my mail here.than they give you some MX records list by saying that tell your resister that your are going to use these MX records for your website mails.Now when an email is sent it may be go to your DNS server but then finally it reaches to google server and your mail finally  outsourced.


CNAME - CNAME maps from one domain name to another domain name.

A - A maps from IP address to domain name.

If I have a website and wants to tell world about my website than what I need to do.for example if I have firstemission.com as my website than first I need to create  A map for my website.
After that If I want to open my mails as mail.firstemission.com despite of that we have our MX records at google server than we need to map CNAME mapping for that.

Virtual Private Server(VPS)- for more control in our server.we can buy VPS.it is good for learning purpose.                                                                                                                         




Friday, 1 March 2013

Prototype in JavaScript


Few Important things before reading prototype :
  • The functions in JavaScript are objects and they contain methods and properties. Some of the common methods are apply() and call() and some of the common properties are length and constructor. Another property of the function objects is prototype.
  • prototype is the property of functional objects. 
  • Only functions and no other object can be used as a constructor in javascript .


1.  Extending an object by adding a custom method can be quite convenient, but it only applies to that particular object's instance. What if you wanted to modify the entire existing class to add new functionality? For this, we use the prototype property.


2.  Adding properties or methods to the prototype property of an object class makes those items immediately available to all objects of that class, even if those objects were created before the prototype property was modified.


3.  Note that adding a public property to a class of objects creates a single value which all instance objects share. However, modifying this value through this.globalPropertyName will result in a local public property of the object being created and set. Modifications to the class-wide property must be made through the prototype property of the class.


4.  Declaring javascript object methods in constructor or in prototype:

a)  If your methods do not use local variables defined in your constructor , then use the prototype approach.
b) If you're creating lots of Dogs, use  the prototype approach. This way, all "instances" (i.e. objects  created by the Dog constructor) will share one set of functions, whereas the constructor way, a new set of functions is created every time the Dog constructor is called, using more memory.


5. Inheritance :

a) You cause a class to inherit using  ChildClassName.prototype = new ParentClass();.
b) You need to remember to reset the constructor property for the class using ChildClassName.prototype.constructor=ChildClassName.
c) You can call ancestor class methods which your child class has overridden using the Function.call() method.
d) Javascript does not support protected methods.
(For detailed study follow : this link )


6. To add a property or method to an entire class of objects, the prototype property of the object class must be modified. The intrinsic object classes in JavaScript which have a prototype property are:
Object.prototype — Modifies both objects declared through the explicit new Object(...) constructor and the implicit object {...} syntax. Additionally, all other intrinsic and user-defined objects inherit from Object, so properties/methods added/modified in Object.prototype will affect all other intrinsic and user-defined objects.
Array.prototype — modifies arrays created using either the explicit new Array(...) constructor or the implicit [...] array syntax.
String.prototype — modifies strings created using either the explicit new String(...) constructor or the implicit "..." string literal syntax.
Number.prototype — modifies numbers created using either the explicit new Number(...) constructor or with inline digits.
Date.prototype — modifies date objects created with either the new Date(...) constructor.
Function.prototype — modifies functions created using either the explicit new Function(...) constructor or defined inline with function(...){...}.
RegExp.prototype — modifies regular expression objects created using either the explicit new RegExp(...) constructor or the inline /.../ syntax.
Boolean.prototype — applies to boolean objects created using the explicit new Boolean(...) constructor or those created using inline true|false keywords or assigned as the results of a logical operator.
(For detailed study follow : this link)



7. Danger of adding methods to Object.prototype:
·         Object.prototype.length = function(){
    var count = -1;
    for(var i in this) count++;
    return count; //appendTo method brock.
  }
           // Do not use this
Object.prototype.load = function () {};
   $(window).load(function () {
  alert('load event'); // never fired
});
Augmenting the Object.prototype object in that way is never recommended, because those properties will be inherited by a great number of objects -even also by some host objects-, and as you know, the primary concern is that they will be enumerated by the for-in statement. Some methods of jQuery liberary are incompatible with extending Object.prototype.
In ECMAScript 5, now a safer way exists, because we can now declare non-enumerable properties, for example:
Object.defineProperty(Object.prototype, 'foo', {
value: 'bar',
 });
In the property descriptor -{ value: 'bar' }- we can specify property attributes, in the case of Value Properties as in the above example, we can specify the writable attribute, and the common configurable attribute (determines if a property can be re-configured -attribute changes- or deleted).
And we have also the enumerable attribute, which determines if the property will be enumerated by the for-in statement.
If we don't specify the attributes, they are false by default, the descriptor will look like:
{
  value: 'bar',
  writable: false,
  configurable: false,
  enumerable: false
}

So far we talked about various points, but from here we are concentrating only in enumeration.

8. About making properties non-enumerable:
Benefit of making properties non-enumerative- I think the main benefit is to be able to control what   shows up when enumerating an object's properties, such as for in or Object.keys().So normally, when people want to add a method to Object, such as a polyfill for some method not supported in old browsers, they modify the .prototype. But that makes the property enumerable and messes up what is returned in loops/keys collection (without using .hasOwnProperty).
So instead of something like:
Object.prototype.myMethod = function () {
    alert("Ahh");
};
you could use Object.defineProperty to explicitly say to have it not be enumerable:
Object.defineProperty(Object.prototype, 'myMethod', {
    value: function () {
        alert("Ahh");
    },
    enumerable: false
});
That way, for example when you use for (var key in obj), "myMethod" won't be an item enumerated, and you won't have to worry about using .hasOwnProperty. The main problem with this is that some browsers don't support it of course: link and that not all libraries/code use it, so you can't always rely on external libraries/code to do use correctly and all the time.
You can access a non-enumerable property at any time you want, it just won't show up when enumerating the object's properties - that's the main point.
And I do believe that all "predefined" properties of objects are non-enumerable. By that, I really only mean native properties, not necessarily inherited or created. So with your example, pop and push will not be enumerated over, but Array.prototype.indexOf will be if it is created as a polyfill on an old browser that doesn't support that method...which of course, can be avoided by using Object.defineProperty like my example above. Another example is the length property, which is not enumerated over.
Here's an example in general: link
The use and definition of Object.keys is important: "Returns an array of a given object's own enumerable properties, in the same order as that provided by a for-in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well)." - from MDN . 

9. There are some details to be aware of:
  • Not all properties show up in a for-in loop. For example, the length (for arrays) and constructor properties will not show up. The properties that do show up are called enumerable. You can check which ones are enumerable with the help of the propertyIsEnumerable() method that everyobject provides.
  • Prototypes that come through the prototype chain will also show up, provided they are enumerable. You can check if a property is an own property versus prototype's using the hasOwnProperty() method.
  • propertyIsEnumerable() will return false for all of the prototype's properties, even those that are enumerable and will show up in thefor-in loop.
Let's see these methods in action. Take this simplified version of Gadget():
function Gadget(name, color) { 
   this.name = name; 
   this.color = color; 
   this.someMethod = function(){return 1;}
}
Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Creating a new object:
var newtoy = new Gadget('webcam', 'black');
Now if you loop using a for-in, you see of the object's all properties, including those that come from the prototype:
for (var prop in newtoy) { 
   console.log(prop + ' = ' + newtoy[prop]); 
}
The result also contains the object's methods (as methods are just properties that happen to be functions):
name = webcam
color = black
someMethod = function () { return 1; }
price = 100
rating = 3
If you want to distinguish between the object's own properties versus the prototype's properties, use hasOwnProperty(). Try first:
 >>> newtoy.hasOwnProperty('name')
true
>>> newtoy.hasOwnProperty('price')
false .

Thursday, 10 January 2013

Best practice with jQuery

 1. How to select your selector ?

There are various ways of selecting a DOM element in jQuery, but performance depend on how we select our selector.faster to slower-
 $(“#id”) - This is the fastest way of selecting a DOM element.because it uses native document.getElementId() method.
 $(“tagName”) - Use of tag name for selector is also very fast, such as for better performance we can use $(“p”), because it uses native document.getElementsByTagname() method.
 $(“.class”) - This also a fast selector but slow in older versions of IE.It uses native document.getElementByClassName() method. because all above methods have their respective native methods so they are very fast. 
 $(“[attribute=name]”) - Selection by using attribute is slow because it does not have any native method in JavaScript.
 $(“:hidden”) - This is the most powerful but slowest selector in all of above so be careful when we use pseudo-selectors.

2. How to use jQuery Object for Chaining ?

An important fact about jQuery is that its almost all methods returns a jQuery object, its mean we can use multiple methods in a single line.It will make our code slightly shorter and more faster.Example:
$(“obj”).addClass(“try”);
$(“obj”).css(“color”,”red”);
$(“obj”).height(100);

by using chaining we can minimize our code as :
$(“obj”).addClass(“try”).css(“color”,”red”).height(100);

3. How to use Cache ?

If you are using a selector more than one times in your code then its better to use caching in your program.It will improve your program performance.
$(“multiply”).find(“id”).addClass(“plus”);
$(“multiply”).find(“id”).removeClass(“plus”);

by using Cache:
var multi = $(“multiply”).find(“id”);
multi.addClass(“plus”);
multi.removeClass(“plus”)
;

by using cache and chaining both:
var multi = $(“multiply”).find(“id”);
multi.addClass(“plus”).removeClass(“plus”);


4. How to handle events in better way ?

“Event-listeners cost memory”
Whenever we are writing a event-listener than always kept in mind the above statement.
Commonly in our code we uses hundreds of event-listener and jQuery provides us various method for that but how to use efficiently these methods is upto us.Example:
$(“table”).find(“td”).click(function(){
          $(this).toggleClass(“active”); })

Here, we are binding an event to each “td” of table which will take more memory,instead of that we can use “on” method which wrap-up functionality of all jQuery’s previous event-listeners (.bind(),delegate(),.live()). additionally “on” support some other parameters also which helps in delegation.
$(“table”).find(“td”).on(“click”,function(){
          $(this).toggleClass(“active”); })

but in above still we are binding our event with each “td” again wastage of memory, so we can use in such a manner.here we are binding event with our table not  in a particular “td”,so here we reduced our memory uses.
$(“table”).on(“click”,”td”,function(){
       $(this).toggleClass(“active”);})



5.How to separate “CSS” and “jQuery” ?

Instead of changing appearances by jQuery directly, we can use CSS classes for changing  appearances.
$(“table”).css(“color”,”red”);
Instead of that we should make a CSS class and then use jQuery methods to implement that class.Such as:
CSS class:
.red{
 color:red;
}

jQuery:
$(“table”).addClass(“red”);
It will provide us more flexibility, we can easily remove that css whenever required.

6. How to store data in jQuery ?

.attr or .data - Many of us use .attr method for storing data, which is not a good practice.Instead of that we should use .data method for storage. .attr method is for manipulating the attribute.So:
$(‘selector’).attr(‘alt’, ‘this is the data that I am storing’);
           // then later getting that data with
          $(‘selector’).attr(‘alt’);

Here we are storing data with HTML, which are not meant to be.Instead of that we store data in our javaScript code,which is a better idea.
Instead of that we should use:
$(‘selector’).data(‘meaningfullname’, ‘this is the data I am storing’);
// then later getting the data with
$(‘selector’).data(‘meaningfullname’);


Updation continue in this article @ click  you can send your suggestion on java.ansh@gmail.com .

Wednesday, 19 December 2012

Working With Node

Node is a server-side JavaScript interpreter that changes the notion of how a server should work.
Its goal is to enable a programmer to build highly-scalable applications and write code that handles
tens of thousands of simultaneous connections on one, and only one, physical machine.Here we
go with practical implementation of node.

Installing Node.js

1. Download setup for your system from http://nodejs.org/download/, and click on install.
2. You will get a node.js command prompt.

3. *npm will also install with your node.js setup.
or
1. Go to http://nodejs.org/ , and click the Install button.
2. Run the installer that you just downloaded. When the installer completes, a message indicates
that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.

*npm, short for Node Package Manager, is two things: first and foremost, it is an online repository

Now we have a command prompt of node.js like as:
Your environment has been set up for using Node.js 0.8.16 (ia32) and NPM.
C:\Users\{USERNAME}>
After Installing Node.js, we will create a build tool for our Applications, for that we will use a build-in
package Grunt by using npm.
We have a project gruntTool, inside it we install grunt package.

Installing grunt

1. Open node.js command prompt.
2. Reach at project directory or you can use mkdir for making new gruntTool directory.
C:\Users\{USERNAME}\workspace\gruntTool>
3. C:\Users\shai\workspace\gruntTool>npm install grunt
for installing locally in your project.
If you want to install globally in your system use
C:\Users\{USERNAME}\workspace\gruntTool>npm install -g grunt
If we install grunt locally it will create a folder ‘node_module’ in our project.


How to use grunt package

Now in windows if we run our run command grunt.cmd, it will give something like this :
<FATAL>Unable to find ‘grunt.js’ config file. Do you need any --help? </FATAL>
For using grunt full potential we needed a ‘grunt.js’ file in our project, for that we use grunt init
command. It gives us five currently available templates:
● jQuery: A jQuery plugin
● node: A node module
● commanjs : A commanJS module
● gruntplugin: A Grunt plugin
● gruntfile:A Gruntfile(grunt.js)

If your project does not belong to anyone you can use final one gruntfile, Because we are creating
a simple tool so we will go with final one.
With command :

grunt init:gruntfile

you will see something like that:
Running “init:gruntfile”(init) task
This task....................................................
…................................................................
…................................................................
“gruntfile”template notes:
….................................................................
….................................................................
Please answer the following:
[?] Is DOM involved in any way? (Y/n)
[?]Will files be concatenated or minified? (Y/n)
[?]Will you have a package.json file? (Y/n)

After answering these questions it will show done, without any errors. We get a package.json and
grunt.js file in our project directory.
In our package.json , we get the information about our version, name, type, dependencies, and
in grunt.js we get grunt.initConfig and grunt.registerTask. In grunt.initConfig we get some default
tasks such as min, concat, lint, jshint, qunit and watch.
In register Task we register out tasks as:

grunt.registerTask('default', 'lint qunit concat min');

So when we use command grunt.cmd (for windows) all four tasks are run by default.
Now we will create a source folder src, in which we have three separate folders for javascript,
html and css. These folders can have other folders inside them.
Our project directory will look like this:

gruntTool
          |__ node_modules
          |__ src
                  |__ javascript
                  |__ html
                  |__ css
          |__ tasks
          |__ target
          |__ grunt.js
          |__ package.json
          |__ config.json


tasks folder: is for creating your own tasks.
config.json file is for creating token.

Create different Environment
Classify the tasks which we want to do in different environment. For example “DEV” and “PROD”
     dev :

                Concat JavaScript .

                Remove temporary files and folders.
               Copy css and html files from src to target.
               Zip your target folder

   Prod :

               concat javascript .

               Minify javascript .
               Minify css.
               Remove temporary files and folders .
               Copy html from src to target .
               Zip your target folder

We can see there are some common tasks which should run in both cases so how we can configure our tasks? We are going to configure tasks according to their environments.

Concat javascript

We have something like
concat: {
    dist: {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: 'target/FILE_NAME.js'
    }
  },

This is the task which is in-build in grunt, now we can divide this task for different environments as follows

concat : {
    prod: {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: 'target/FILE_NAME.js'
    },
     dev : {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: ‘target/FILE_NAME.js'
    }
  },

Here, we can see our task is divided in different environment. And we can register tasks as:

grunt.registerTask('dev', 'lint qunit concat:dev min');
grunt.registerTask('prod', 'lint qunit concat:prod min');

For running our dev tasks we use command
grunt.cmd dev

For running our prod tasks we use command
grunt.cmd prod  .

Register your config.json file

For tokenizing or making task for scalable we use a config.json file and register file in our grunt.js file as:
config : '<json:config.json>'

Minify css

We have various ways of minifying css, grunt build-in function min in only for the minification of javascript(till now).we will try two approaches for minification.
By using YUI compressor

1. Download the jar file in your project directory from http://www.java2s.com/Code/Jar/y/Downloadyuicompressor247jar.htm  .
2. Write a task in your tasks folder ‘mincss’ as :
   var exec = require('child_process').exec;
    grunt.registerTask('mincss', function() {
      grunt.log.write("Minifying css using yuicompressor \n");
      var cmd = 'java -jar -Xss2048k ' + __dirname
              + '/jar/yuicompressor-2.4.7.jar --type css ' // Explicitly download YUI compressor.
              + grunt.template.process('<%= config.data.src %>*.css') + ' -o '                 + grunt.template.process('<%= config.data.dest %>main.min.css')
      exec(cmd, function(err, stdout, stderr) {
          if (err)
              throw err;
      });
  });

we can see we are using exec in our task so we need to require child_process package, which we can install as npm install child_process .
3. Now we need to register our task in grunt.js file as:
 grunt.task.loadTasks('tasks');
4. Now we can register our mincss task as
grunt.registerTask('prod', 'lint qunit concat:prod mincss');

Finally we are able to minify our css.One more thing we are using config.json file for our address which would look like as:
  {
"data": {
    "src"       : "src/**/*"
    "dest"      : "target/"
}
}

but this is very complex, let’s try another one.

By using grunt-css package
1. Install npm install grunt-css  .
2. Register your task in grunt.js file as
 grunt.loadNpmTasks('grunt-css');
3. Now structure of cssmin task put in your grunt.js file as :
 cssmin : {
          files : {
              src : '<%= config.data.src %>*.css',
              dest : '<%= config.data.dest %>/main.min.css'
                  }
              },
4. Register your task for environment as :
 grunt.registerTask('prod', 'lint qunit concat:prod cssmin');
These are two ways of css compression. I personally feel that second one is better than first because of its less complexity.  

Copy files
If we need to copy some files from src to target than, we need to install another package as :
1. npm install grunt-contrib
2. Load your package in your grunt.js file as:
  grunt.loadNpmTasks('grunt-contrib');
3. Task writing :
  copy: {
         prod : {
     files : {
      "<%= config.data.dest %>" : "<%= config.data.src %>.html",
              }
          }
          },

4. Register your task for suitable environment as:
   grunt.registerTask('prod', 'lint qunit concat:prod mincss copy’);
  
Zip folders

Now for zipping a folder we need to install a new package as :
1. npm install grunt-contrib-compress  .
2. Load your package for grunt.js file as :
  grunt.loadNpmTasks('grunt-contrib-compress');
3. Task writing :
   compress : {
          zip : {
                files : {
          '<%= config.data.dest %>.zip' : '<%= config.data.dest %>/**'
                  }
                }
          },
4. Register your task for suitable environment as:
     grunt.registerTask('prod', 'lint qunit concat:prod mincss copy compress’);


Clear temp files
During the execution of various tasks, sometimes we create various temp files or folders, at last we need to remove that folders and files from our project. For that we use another package as :
1. npm install grunt-clean
2. Loading task as :
  grunt.loadNpmTasks('grunt-clean');
3. *task writing:
  clean : {
          folder : "target/",
          file : "temp/"
         },
             
  * Syntax of task should be correct, src and target addresses should be correct, because it is not a stable version and it sometimes deletes your whole project. So everything should be written in correct way.
4. Register your task for suitable environment as:
     grunt.registerTask('prod', 'lint qunit concat:prod mincss copy clean compress’);

Note:
Apart from that if you are using grunt-cli latest version of grunt than keep in mind following points:
During installation follow the following instruction otherwise it will give you fatal error.

Solution for v1.4
1. npm install -g grunt-cli
2. npm init
  fill all details and it will create a package.json file.
3. npm install grunt (for grunt dependencies.)