Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

Apr 14, 2020

React Introduction

React helps you build encapsulated components that manage their state, then compose them to make complex UI. The component has Props & State which represents its model. The data flow one way down the component hierarchy. 

state => view => action => state => view

View


The view is the direct result of rendering DOM using ReactDOM.render from the react-dom package. For a given model the DOM will always be the same, so the only way to change DOM is to change the model. Once a model is rendered in DOM, it can generate events that feedback into the state and trigger another render cycle. Once a state is changed react will render DOM. A state is always owned by one Component. Any data that’s affected by this state can only affect Components and its children. Changing state on a Component will never affect its parent, or its siblings, or any other Component in the application.

For efficient rendering, React maintain its document obstruction. A component render function updates this fake document object model known as the virtual DOM which is extremely fast. Once that happens react compares the fake document object model to the real document object model and update the real document object model in the most efficient way possible. Updating DOM is an expensive operation as redrawing large sections of DOM is inefficient. The comparison of virtual DOM with a real document happens in memory. 

ReactDOM takes two arguments: the first argument is JSX expression and the 2nd argument is dom element, this is the place where the react component will be inserted into the DOM element.

JSX


It's an XML like syntax extension to javascript which is used to describe how UI will look like. You can put any valid JavaScript expression inside the curly braces in JSX. Since the browser doesn't understand JSX, so it must be compiled to javascript, which is handled by bable. You may have an option to write directly the javascript and not JSX, but that may not be easier to write/read/maintain. If you are interested you can use https://babeljs.io/ to see how JSX is compiled to javascript. Writing HTML in javascript looked a little weird if you come from the angular background, but if you really think even in angular you write javascript in angular HTML like ngFor, etc. So either way, you have one of the two options - write js in HTML or HTML in js. One advantage I see with HTML in js is that at compile time you can catch an error. There are few minor differences between JSX and HTML like className for class and htmlFor for for. JSX can represent two types of element

  • DOM tag like div, dom tags are written in lower case, attributes passed to these elements are set on rendered DOM
  • User definer element must be starting with a capital letter. attributes to user-defined elements are passed to the component as a single object, usually referred to as props. All react components must act like pure functions with respect to their props, for a given prop output should be same and component needs to be rendered only if prop changes

Props and State


Props is short for properties. It allows you to pass data to the child component. Props are immutable as they are passed down from parent to child, so they are owned by the parent, so you cannot change it. On the other hand, the state is used to hold data that your component need to change for example value of the text field. To update state you use setState

Event


React events (called synthetic event) are very similar to dom events, with few minor differences like name with camel case compare to lower case and function being passed as event handler rather than string. To prevent default you need to call preventDefault on the event object. SyntheticEvent are cross-browser wrapper around the browser’s native event. You can access browser native event by accessing nativeEvent. Since data flow one way, the only way to pass data is to raise event and update state which will eventually trigger view update. The same way you can pass data to the parent component, by calling function passed in the props.

Angular vs React

Both are component-based platform-agnostic rendering frameworks/tools, which you can write using typescript or javascript.

Data Binding
Angular uses two-way data binding which helps write less boilerplate code to have a model and view in sync. React supports one-way data binding which makes debugging easier and maybe help in performance

Architecture
Angular is a full-blown framework that includes DI, forms, routing, navigation, HTTP implementation, directives, modules, decorators, services, pipes, templates with few advanced features like change detection, Ahead-of-Time compilation, lazy loading,  and Rx.js. This is built into core of the framework. React is much simple and you will have to use other libraries like redux, react-router, etc to make a complex application. React has a wider range of material design component libraries available.

CLI
Angular cli is a powerful command-line interface that assists in creating apps, adding files, testing, debugging, and deployment. Create React App is a CLI utility for React to quickly set up new projects


Apr 28, 2019

ES6 New Fetures

let and const

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope, which means following is valid
 x=5
 var x
 y === 7 //false, as declaration is hoisted but not the initializations
 var y = 7;

JavaScript only hoists declarations, not initializations.
var is function scoped which sometimes is confusing. Refer following example

 if(true){
   var x = 20
 }
 console.log(x) //this will log 20

Even though x is declared inside if block, but since var declaration are hoisted it will be accessible anywhere within the function.

In ES6, let and const was introduced which is blocked scoped and is align with other programmable language like c#, java. In the above example, if you change var to let, it will throw error as you try to access x outside if block where its declared.

Arrow function

This is defined as anonymous function much like lambda function in c#

Destructuring Assignment

This make it possible to unpack values from array, or properties from objects, into distinct variables.

[a, b, ...rest] = [10, 20, 30, 40, 50];//a=10,b=20,rest=[30,40,50]

const o = {p: 42, q: true};
const {p: foo, q: bar} = o;

function someMethod({p: foo, q: bar})

This can be used even for nested object.

Rest parameter give you access to remaining items in the from of array which makes it lot easier to run any of array method on that.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
var arr2 = [...arr]; // like arr.slice()
var concat = [...arr1, ...arr2];

var clonedObj = { ...obj1 };
var mergedObj = { ...obj1, ...obj2 };

Template literals

`Hello ${name} !!`

Can also be used with multi line

ES6 Module

ES6 provides build-in module in javascript, earlier to this you have to use library like commonjs, amd


ES6 Class


Jul 17, 2018

Common Collection Methods in Javascript and C#

Transform each element of collection into a new form and return new array 
javascript  
[1, 2, 3].map(x => x * 2);
c#
(new int[] {1, 2, 3}).Select(x => x * 2)

var students1 = new[] {
 new { Id = 1, FirstName = "John", LastName = "Singh", Addresss=new []{ new {City = "Boston" }, new { City = "Quincy" } } } ,
 new { Id = 2, FirstName = "Json", LastName = "Jha", Addresss=new []{ new {City = "Cambridge" } } }
 };
foreach ( var item in students1.SelectMany(y=>y.Addresss,(a,b)=> new { a, b} ) ) {
 Console.WriteLine($"{item.a.FirstName}-{item.b.City}");
}
Filters collection 
javascript
[1, 2, 3].filter(x => x > 2)
c#  
(new int[] {1, 2, 3}).Where(x=>x>1)
Accumulator function over a collection 
javascript  
[1, 2, 3].reduce((accumulate, currentValue, index) => accumulate + currentValue, 10)
c#
(new int[] {1, 2, 3}).Aggregate(10, (accumulate, currentValue) => accumulate + currentValue)
Determines whether a collection contains any elements which pass the test 
javascript
[1, 2, 3].some(x=>x>2) //true
[1, 2, 3].some(x=>x>3) //false 
c#
(new int[] {1, 2, 3}).Any(x=>x>2) 
Determines whether all elements of collection pass the test 
javascript
[1, 2, 3].every(x=>x>0) //true
[1, 2, 3].some(x=>x>1) //false 
c#   

(new int[] {1, 2, 3}).Any(x=>x>2) 
(new int[] {1, 2, 3}).All(x=>x>2)
Find first element of collection that pass the test 
javascript  
[1, 2, 3].find(x=>x>1) //2
[1, 2, 3].find(x=>x>7) //undefined
[1, 2, 3].findIndex(x=>x>0) //0
[1, 2, 3].findIndex(x=>x>7) //-1
c#  
(new int[] {1, 2, 3}).First(x=>x>1) //2
(new int[] {1, 2, 3}).First(x=>x > 7) //InvalidOperationException 
(new int[] {1, 2, 3}).FirstOrDefault(x=>x3) //0

(new int[] { 1, 2, 3 }).ToList().Find( x => x > 0 ) //0
(new int[] { 1, 2, 3 }).ToList().Find( x => x > 7 ) //0
(new int[] { 1, 2, 3 }).ToList().FindIndex( x => x > 7 ) // -1
Concatenates two Collections 
javascript
[1, 2, 3].concat([4, 5, 6])
[...[1, 2, 3],...[4, 5, 6]]
c#
(new int[] {1, 2, 3}).Concat(new int[] {4, 5, 6})
GroupBy 
javascript
[{name:'John', city:'Quincy'},{name:'Sam', city:'Boston'} ,{name:'Json', city:'Boston'}]
  .reduce((a,c,i)=>{
    let element = a.find(x=>x.key === c.city);
    element ? element.item.push({name:c.name}): a.push({key:c.city, item:[{name:c.name}]});
    return a;
  }, [])  
c#
var students = new[] { new { Id=1, FirstName = "John", LastName = "Singh" }, new { Id = 2, FirstName = "Json", LastName="Jha"} };
var address = new[] { new {StudentID =1, City = "Boston" }, new { StudentID = 1, City = "Quincy" }, new { StudentID = 2, City = "Quincy" } };
var query1 = students.
 Join( address, s => new { s.Id }, a => new { Id = a.StudentID }, ( s, a ) => { return new { Name = s.LastName + "," + s.FirstName, a.City }; } ).
 GroupBy( x => x.Name );
foreach ( var item in query1 ) {
 Console.WriteLine($"{item.Key}-{item.Count()}");
}
Sorting 
javascript  
console.log([{name:'John', age:42},{name:'Sam', age:25}].sort((x,y)=>x.age-y.age))
c#  
var a = new int[] { 1, 2, 3, 5 };
a.OrderBy(x=>x) //here x should implement ICampare
Slicing 
javascript
var number = [ 1, 2, 3];  
console.log(number.slice(0,2,))//1,2 (will not include end index), number object is not modified
console.log(number.splice(1,2,4)) //[2,3] starting from index 1 take out two and add 4 at the end  
console.log(number) //1,4

number = [ 1, 2, 3];  
console.log(number.shift());//1
console.log(number) //2,3
number = [ 1, 2, 3];  
console.log(number.pop());//3
console.log(number) //1,2

c#
var a = new int[] { 1, 2, 3, 5 };
a.Skip( 1 ).Take(2); //[2,3]
a.Take(1).Concat(a.Skip(3)) //[1,5]
a.Take(1).Concat(new int[]{4}).Concat(a.Skip(3)) //[1,4,5]
var b = new List<int>(){ 1, 2, 3, 5 };
b.RemoveAt(2);//remove 2nd item
b.Remove(5);//remove item with value as 5

Add New Item
javascript
[1,2,3].push(4)// add 2 to end
[1,2,3].upshift(0)//add 0 to starting

c#
stIndex(x=>x=
(new List<int>(){1,2,3,2,5}).Add(6) (new List<int>(){1,2,3,2,5}).Insert(0,0)
Index Of Item 
javascript
[1,2,3,1].indexOf(1,2)///eturn 3
c#
Array.IndexOf( [1,2,3,1], 1, 2 ) //return 3
(new List<int>(){1,2,3,2,5}).FindIndex(x=>x==2);
(new List<int>(){1,2,3,2,5}).FindLastIndex(x=>x==2);


String to Character Array 
javascript  
'this is string'.split('');
'this is string'.split('').join('');
c# 
"this is string".ToCharArray();
new String("this is string".ToCharArray());
String Split 
javascript  
'this is string'.split('is');
c# 
"this is string".Split(new char[]{'i', 't'}, StringSplitOptions.RemoveEmptyEntries);
"this is string".Split(new string[]{is, str},StringSplitOptions.RemoveEmptyEntries );
Substring 
javascript  
'abcdef'.substring('0,3');//abc start index and end index not include end index
c#
"abcd".Substring(1,2);bd//start index and length

Join Collection of String
javascript  
'this is string'.split(' ').join(',');
c# 
string.Join(",","this is string".Split(" "))
https://javascript.info/string

Apr 18, 2017

js object property descriptor

javascript properties has descriptors called property descriptors. You can access property descriptors like this
  
 var person ={
  name: {lastName:'xyz', firstName:'abc'},
  age: 15
 }
 console.log(Object.getOwnPropertyDescriptor(person,'name'));

This should return
  
 {
  value: object, //this could be value for primitives type property
  writable: true, 
  enumerable: true, 
  configurable: true
 }

You can update these descriptors by using Object.defineProperty
   
 Object.defineProperty(person,'age',{value:5});

Updating writable property descriptor to false will make this property read only
   
 Object.defineProperty(person,'age',{writable:false});

After doing this you won't be able to update property value
  
 person.age = 11; // This will throw error as it cannot assign to read only age property

In the following case we are making name property to be read only, but you can still update any of the property of name object as you not changing name property reference
  
 Object.defineProperty(person,'name',{writable:false});
 person.name.lastName = 'xyza'

If you want to prevent this to happen you can use
  
 Object.freeze(person.name);

After this you wont be able to update lastName
  
 person.name.lastName = 'xyzab' // This will throw error as it cannot assign to read only age property

Updating configurable to false will prevent from redefining the property. You will not be able to change enumerable/configurable property descriptor. You will also not be able to delete the property.
  
 Object.defineProperty(person,'age',{configurable:false}); 

Following will throw error
  
 Object.defineProperty(person,'name',{enumerable:false}); //cannot redefine property age
 Object.defineProperty(person,'name',{configurable:false}); //cannot redefine property age
 delete person.age //cannot delete property age

You will still be able to change writable descriptor
  
 Object.defineProperty(person,'age',{writable:false}); 

Updating enumerable to false will prevent this property to be enumerated
    
 Object.defineProperty(person,'age',{enumerable:false}); 

After executing above line you wont be able to see age property in any of the below code
   
 for (var propertyName in person){
    console.log(propertyName + ": " + person[propertyName])
 }
 console.log(Object.keys(person))

  console.log(JSON.stringify(person))  

Apr 15, 2017

javascript prototype

A function's prototype is the object instance that will become prototype for all objects created using this function as a constructor. For example when you define following function a prototype property is created on Foo, which you should be able to access Foo.prototype and it will be initialized object (like {}) with no property.
 
 function Foo(){
   console.log("js will create prototype property on Foo which will be initialized as empty object {} ");
 }

You can add property to the prototype object of Foo Foo.prototype.myFirstName = "Sam" Now when you create object using constructor function then constructor function prototype will become object prototype
 
 var foo = new Foo();
 var bar = new Foo();
 Foo.prototype.myLastName = "Adam"

So following should return true
 
 console.log(bar.__proto__=== Foo.prototype);
 console.log(foo.__proto__=== Foo.prototype);

You can add more properties to Foo prototype
 
 Foo.prototype.age = 5

Now lets say you update functions prototype like this. Here you changing pointer of Foo.prototype where as in the above case pointer was same, you just added new property to that object.
 
 Foo.prototype = {myName: "Tom"}

Doing so will change return value of following to false as bar and foo prototype is still pointing to prototype object which was there on Foo when foo and bar was created.
 
 console.log(bar.__proto__=== Foo.prototype);
 console.log(foo.__proto__=== Foo.prototype);

So now when you create new Foo object this will get new prototype
 
 var baz = new Foo();
 console.log(baz.__proto__=== Foo.prototype);

There is a chain of prototype. Following will return true
 
 console.log(bar.__proto__.__proto__=== Object.prototype);
 console.log(bar.__proto__.__proto__.__proto__=== null);

When you try to access foo.myFirstName, javascript looks first if myFirstName is property of foo or not, if not then it looks in the prototypal chain and return it. So in the above case foo.hasOwnProperty('age') will return false where as foo.__proto__.hasOwnProperty('age') will return true. Also you can check by looking at all the keys Object.keys(foo

). When you create an object with new keyword following happens
  
 function Foo(name){
  var someInteger = 1;
  this.name = name;
  return 5;
 }
 var foo = new Foo('John');

A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its "this" parameter. For all other functions, the default return value is undefined. So in the above case foo will be assigned like this
 
  Foo {
   name: 'john'
  }

foo object will not see someInteger and its return value Function prototype (Foo.prototype) object is passed to the __proto__ property of the object so this will return true
 
  console.log(foo.__proto__=== Foo.prototype); //will return true

When you create an object by Object.create() only prototype is set
 
 var foo = Object.create(Foo.prototype);
 console.log(foo.__proto__=== Foo.prototype); //will return true
 console.log(typeof foo.name1 === 'undefined'); //will return true
 console.log((foo.name1 === undefined ); //will return true

When you create an object by object literal {} then Object prototype is set prototype of the object
  
 var foo = {firstName: 'John', lastName: 'singh'};
 console.log(foo.__proto__ ===Object.prototype); //will return true

Dec 23, 2016

why web component

Undescriptive Markup - Currently we have deeply nested makeup (div/span), which sometimes becomes harder to understand/maintain. Refer any of the popular web page source and you will find deep nested mark up. Though some provide meaningful id/class.

Style conflicts - There is no guarantee that css from one part of the page will not conflict to other.

No native templates - Template is a mechanism for holding client-side content that is not to be rendered when a page is loaded, but may be subsequently be instantiated during runtime using JS. Its a content fragment that can be used in the document.

HTML Imports - There is no way to include and reuse HTML documents in other HTML documents.

No bundling - You cannot bundle css, javascript, html together. like bootstarp need to have at least 3 reference - jquery,bootstrap js and css. 

No standard - Multiple library like jQuery, angular (directive), bootstrap provide their own convention, but there is no standard. 

HTML5 Web component addresses these issues, by using combination of following four technologies.
  • Template
  • Shadow DOM
  • Custom Element
  • HTML Import

Mar 28, 2016

angularjs - Directive

Directive gives html new functionality. Angular parses html, it looks for directives and take action. for example for ngClick it will register click event on that dom object. There are four way to write directive and not all directive support all four way
<ng-form/>  tag
<div ng-click> attribute
<div class="ng-form"/> class
html comment

Event Directive
These respond to the specific event and let you call a method on your scope.
ngClick
ngDblClick
ngMousedown
ngMouseenter
ngMousemove
ngMouseover
ngMouseup
ngChange require ng-model to be present

OtherDirective
ngApp = designates the root element of the application
ngBind
ngBindTemplate - can use template and use multiple items
ngBindHtml - depends on ngSanitize module, may remove anything unsafe
ngBindHtmlUnsafe -
ngHide
ngShow
ngCloak - It will hide html element until angular processes all the directives and document is ready to be displayed. It is specially helpful on slow m/c. This avoid flash of unbound html. Look for css rule from the documentation
ngStyle
ngClass
ngClassEven repeat directive
ngClassOld

Thease are specially helpful in case browser doesn't it
ngDisabled
ngChecked
ngMultiple
ngReadonly
ngSelect

ngForm - It allow nested form
ngSubmit
ngHref - This will be used with anchor tag, it will not add this attribute to the element until angular has chance to process it.
ngScr - this allows to bind an image source. This delays binding untile angular replaces source of the image
ngNonBindable - angular doesn't parse text in that


Expression
Angular expressions are JavaScript-like code snippets which you can add to html. For example {{2*2}} will get display as 4. It doesn't support all javascript syntax

Filters
Filters are used to modify Output before it's rendered by the browser. Its used for formatting, Sorting dataset and Filtering dataset.

{{ expressiob | filter }}

uppercase
lowercase
number {{123.123 | number : 2}}
currency {{123.123 | currency}}
date {{<JS date> | date: 'mediumDate'}}
json can be used to print json object
orderBy used with ng-repeat
ng-repeat="employee in oemployees | orderBy:name"
limitTo
filter
ng-repeat="employee in oemployees | orderBy:name |limitTo: 3 | filter: {claim: {patientAccountNumber: ''}}"

Validation
You can use build in directive (ng-required="true" ng-pattern="onlyNumbers") to do validations. There are few form properties which you can use for styling example - Dirty, invalid, Pristine (exact opposite of dirty), valid (which is the exact opposite of invalid). Angular sets css class on input field to indicate what state those fields are.



Jun 9, 2014

Knockout

Knockout.js is a javascript library that allows two ways bindings between html elements and data model. This means any changes to data model can be automatically reflected in DOM and vice-versa. It simplifies dynamic javascript ui with MVVM pattern.

Observables are Functions
This was little confusing in beginning and probably I spend a lot of time in order to understand this.

var personModel = {
    firstName: ko.observable(''),
    lastName: ko.observable(''),
}

This is how you access and set these properties.

var firstName = personModel.firstName();
personModel.lastName('Raj');

Observable Arrays Track Arrays, Not the Items Within
An observableArray also has some extra methods added to it to perform basic array operations-pop, push, shift, unshift, reverse, sort, splice,remove,removeall.... Refer this for complete list

ko.toJS
You get a plain copy that contains only your data and no Knockout-related artifacts

ko.toJSON
This can be used for debugging too, something like this.
<hr />
<h2>Debug</h2>
<div data-bind="text: ko.toJSON(viewModelCart)"></div>

Manual Subscription
In typical scenarios you won't need manual subscription but sometimes it becomes handy. Consider an example where you have drop-down and based on the drop down selection, you want to make an ajax call, so you can write something like this.
viewModel.selectedItem.subscribe(function(newValue) {
    //make ajax call
});

knockout.mapping plugin.
Sometime using mapping plugin saves a lot of time. You can use ignore/include to have more control while mapping.

computedObservables

knockout.validation
Very handy in terms of applying validation logic.

Adding static text on data binding
This will not work
data-bind="text: '$' + Amount"

you have to use
data-bind="text: '$' + Amount()"
or 
data-bind="text: '$' + ko.utils.unwrapObservable(Amount)"

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();
 

Feb 28, 2012

jQuery Deferred object

You can create a Deferred object like this

var dfd = $.Deferred()

As of now this goes to the pending state (or unfulfilled)

you can add as many number of then(),done(),fail() which is kindof event. These are callbacks which are called once deferred object is resolved or rejected. So you can consider these as listener which can be triggered by calling resolve or reject.
 

  dfd.done(function(){
   alert("deferred object got resolved");
  })
  
  dfd.done(function(){
   alert("I am also notified that the deferred object got resolved");
  })
  
  dfd.fail(function(){
   alert("deferred object got rejected");
  })
  
  dfd.then(function(){
   alert("deferred object got resolved");
  },function(){
   alert("deferred object got rejected");
  }
  )

Once you resolve or reject deferred object it goes into resolved (fulfilled) or rejected (failed) state. When the Deferred is resolved, any doneCallbacks added by done or then are called in the order they were added. Similarly for reject, it call fail or fail part of then.
 
  dfd.resolve();
  dfd.reject();

State 
Deferred object has state which you can get from dfd.isResolved() or dfd.isRejected(). The state is persistent, which means once resolved or rejected it will maintain its state forever. After this any then/done/fail called will be executed immediately.

Promise
This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe. isResolved, and isRejected) to prevent users from changing the state of the Deferred.

dfd.promise();

If you return deferred object it gives the caller access to resolve or reject directly. So if you don't want caller to have that access then you can return promise object.

Real word example

1. jQuery ajax has been implement using deferred. Now when you do $.get("jQuery-Deferred.html"); it returns Promise object which is read only (It exposes only the Deferred methods needed to attach additional handlers or determine the state, but not ones that change the state )
 
  var req = $.get("jQuery-Deferred.html");
  req.done(function( response ){
     alert("ajax call done");
   });
  req.fail(function( response ){
     alert("ajax call failed");
   }); 

2. Convenient Wait function
 
 function timedMsg()
 {
  wait(1).done(function(){alert("I am displaying after 1 second");});
  wait(11).fail(function(msg){alert(msg);});
 }

 function wait(time) 
 {
  var dfd = $.Deferred();
  if(time < 10){
   setTimeout(dfd.resolve,time*1000);
  }
  else
  {
   dfd.reject("User will not like more than 10 second of wait time.");
  }
  //By returning promise I make sure that the caller doesn't have ability to reject or resolve.
  return dfd.promise();
 }


3. Efficient ajax call
 
 function someCostlyTaskLikeAjax(url) 
 {
  alert("someCostlyTask is called");
  var time = 1;
  var dfd = $.Deferred();
  setTimeout(dfd.resolve("I am resolved"),time*1000);
  return dfd.promise();
 }
 
 function cachingDeferredObject(){
  
  var cache = {};
  
  function fetch_some_object(key){
   if (cache[key]) { 
    alert("I am coming from cache - " + cache[key]);
    return cache[key]; 
    }
    
   return cache[key] = someCostlyTaskLikeAjax(key).done(function(msg){
    //cache = msg;
    alert("From done handler -" + msg);
    return msg;
   });
  }
  
  $.when(fetch_some_object("someurl")).done(function(a){
   alert("1St call - " + a);
  })
  
  $.when(fetch_some_object("someurl")).done(function(a){
   alert("2nd call -" + a);
  })
  
 }