Feb 23, 2014

Backbone intorduction

Backbone is a JavaScript library for building rich web application. It's not a framework(like MVC or MVVM framework). The definition from the Backbone documentation: Backbone.js give structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON.

In a typical client side application, the server's responsibility is to serve the initial page and then provide RESTful web services for the client-side models. The advantage is, its fast, just an initial cost of downloading and after that the network traffic is JSON models and that too asynchronous. The application is running on the client, so there is no round trip to process every single interaction. On the other hand client side application are not automatically indexed by search engine, relatively difficult to test. Also user of the application has source code so are free to modify code, this must be taken into consideration and security must be enforced by the server.

Single Page Application
In a single page application all the resources are loaded as a single page load and then it executes in a single web page, by using Ajax. In a typical server side application the performance suffers because of continuous regeneration of the page and retransmission over the network. SPA moves UI generation and logic to the client. SPA is a concept, not a strict definition. It often makes sense if your application to consist of a set of SPAs.

Model
Its contains application state as well as logic and behaviour. They can be validated, synchronized to some data source and can raise events for state change. Model attribute holds data, which can be accessed by Get,Set,Escape methods. Models have save, fetch, and destroy methods for synchronizing with the server. ToJSON converts a model's attributes to a JavaScript object.
 
 var Product = Backbone.Model.extend({
        prop1: '1',
        initialize: function () {
            console.log('product created');
            this.on('invalid', function (model, error) {
                console.log(error);
            });
        },
        dump: function () {
            console.log(JSON.stringify(this.toJSON()));
        },
        defaults: { // The default's property specifies default values to attributes.
            'name': 'backboan',
            'price': 'free'
        },
        validate: function (attrs) {
            var productIsValid = function(attrs) {
                if (!attrs.name) return false;
                if (!$.isNumeric(attrs.price)) return false;
                return true;
            };
            if (!productIsValid(attrs)) {
                return "please specify valid name and price ";
            }
        }
    });
  
 var p1 = new Product({
        name: 'car',
  price: 'bogus'
    });
 
 console.log(p1.isValid());  
 p1.set('price',10);
 console.log(p1.isValid());  
 console.log(p1.isValid());  
Inheriting Model
 
 var Product = Backbone.Model.extend({});
 var Electronic = Product.Model.extend({});
 
It is possible to define class properties by providing a second argument to extend, and that can be accessed as static method
  
 var Product = Backbone.Model.extend({},
    {
  callmedirectlyonclass: function() {
        return alert('i am static method');
    }

});

    Product.callmedirectlyonclass();
 
View

Routing
Client-side routes are a way to change browser URL which helps in generating a bookmarkable URL or to generate browser history that can be navigated backwards and forwards.Routes can be triggered in two ways:
1. When user enters the url,referesh,back button etc.In this case server process the request as any other request and when the response has been loaded in the browser, the backbone router will try it match it to a route. If a match is found route function will be called.
2. The other thing is client initiated request. These doesn't trigger server request.
 
    var AppRouter = Backbone.Router.extend({
        routes: {
            '': function () {

            },
            ':productName': function (productName) {
                detailProduct(productName);
            }
        }
    });

    appRouter = new AppRouter();
    
    Backbone.history.start();

Collection
Collections groups related models together. Like models it can publish events like model added, model removed, model changed, model destroyed, collection synchronized, collection reset and validation error. These also have lot of iterator methods like add,remove,reset,push,pop,slice,sort, where, findwhere, comparator etc. By default there is no comparator for a collection. If you define a comparator, it will be used to maintain the collection in sorted order.

Feb 20, 2014

Javascript Basics

A robust function can accept any number of parameters, whereas in normal function number of parameters accepted is preset, and cannot be altered.
 
 function addition(){
  var total =0;
  for (i=0;i>addition.arguments.length;i++)
  {
   total += addition.arguments[i];
  }
  return total;
 }

 console.log(summation(3,5));

By using named arguments in JavaScript functions you don't have to rely on order, but instead their name when passing into functions.
 
 function addition( oArg ){ 
  with(oArg){ 
   return  (typeof(number1)=="number"?number1 : 0) + (typeof(number2)=="number"?number2 : 0) ; 
  }
 }
 
 console.log(addition({number1:1,number2:2,number3:3}));

        //typeof returns: number,string,boolean,object,null,undefined

Creating Object Using Object Literals
In JavaScript, and I'm not talking specifically about the browser here, there's a default/global object. It's as if every code that we write which seems to be just "loose" inside your script (i.e. outside of any object declaration) is actually being written in the context of that global object. In our case, that function isn't just a loose "global" function, it's a method of the global object. Bringing ourselves back to the browser, the global object is mapped to the window object in this environment.
 
 function CreatingObjectUsingObjectLiterals(){
  person = new Object(); //or person = {};
  person.Name = "Name";
  person.SayYourName = function(){
   alert("My name is " + this.Name);
  }
  //In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
  person.SayYourName();
 }
 
 //In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
 var CreatingObjectUsingObjectLiterals1 = {
  name : {firstName : "first",lastName :"last"},
  gender : "Male",
  sayHello: hello
 } 
 
 function hello(arg){
  return "hello " + arg;
 }

 CreatingObjectUsingObjectLiterals();
 console.log(window.CreatingObjectUsingObjectLiterals1.sayHello("Test"));
 console.log(CreatingObjectUsingObjectLiterals1.name.firstName);
 console.log(window.hello("Test"));
//How do I loop through properties in an object?
 for(x in CreatingObjectUsingObjectLiterals1) alert(x + "-" + CreatingObjectUsingObjectLiterals1[ x ])

Use a function to define an object, then create new object instances.
 
 function DefineObjectUsingFunction(r){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=r,
  this.diameter=computeDiameter
 }

 var a = new DefineObjectUsingFunction(2);
 console.log(a.diameter());


Define Singleton Object Using Function
 
 //define a function (an anonymous constructor function) and invoke it with new.
 var defineSingletonObjectUsingFunction = new function DefineSingletonObjectUsingFunction(){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=0,
  this.diameter=computeDiameter
 }
 
 defineSingletonObjectUsingFunction.radius = 2;
 alert(defineSingletonObjectUsingFunction.diameter());


Prototype is a type of inheritance in JavaScript. We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.
 
 function DefineObjectUsingFunction(r){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=r,
  this.diameter=computeDiameter
 } 
 
 var a = new DefineObjectUsingFunction(2);
 alert(a.diameter());
 
 DefineObjectUsingFunction.prototype.area = function(){return this.radius*this.radius*3.14;}
 alert(a.area());
 

Using prototype to extend pre-built string() object functionality
 
 function outputbackwards(){
  for (i=this.length-1;i>=0;i--)
  document.write(this.charAt(i))
 }
 String.prototype.writeback=outputbackwards
 var message1="Welcome to my site!";
 message1.writeback();