Monday, 26 January 2015

Config and Run Function Block Lesson 11

Introduction

Every module consist of name and dependencies on zero or more modules, a "config"  method, and a "run" method. Config and run blocks are executed as soon as the module containing the block is loaded into the memory. 

Config & Run Execution Sequence
AngularJs orders all modules in dependency chain according to their dependencies, and then first executes the config method of each module in order of their dependency [execute for first dependency then second and so on, and finally the main module blocks], and then executes the run blocks of each module in the same orders.

In the above example execution sequence of run and config is as described below.

1) In dependent config block.
2) In dependent second config block.
3) In main config block.
4) In dependent run block.
5) In dependent second run block.
6) In main run block.

From the above example it is clear that first inner dependent module code blocks execute and then main module code block execute.

Let us see diagrammatic representation of the same.

Config Code Block
Config code block get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
Source: angular.org

In config blocks we can configure our providers to get more control over services, we can look later on about the providers when we dive into the services also in routing section we will see how they are implemented in angular routing.

See below the code snippet how config works with provider



Run Code Block

Run block get executed after the injector is created and are used to kickstart the application. Only "instances " and "constants" can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
Source: angular.org



AngularJS Custom Filters Lesson 10

Custom Filters

At some point of time we came across the situation where we need some filtering and formatting of data based upon some particular conditions.Our existing filters do not help us and finally we have to come up with our custom solution i:e custom filters.

Syntax For Creating  Custom filters
1) Add filter
2) Provide it name & callback function
3) Return anonymous function with filtered data.
4) In anonymous function, pass data need to be filtered as first parameter & then any other parameters.


My First Custom Filter In Action



Above filter takes the number array and return the set of even numbers.

Summary

1) Filters are used to filter and format data.
2) We can apply filter at html with the help of | symbol & pass parameter to filter with : symbol.
3) We can apply filter in JavaScript controller using $filter service,
4) We can create custom filters and chain them to any angular module.
5) Filter are function to which we pass input to get required result.

Sunday, 25 January 2015

AngularJS Filters Lesson 9

Introduction

When developing any application sometimes we need to format data and require filtering of data, at that point of time filters would be the good choice to implement that logic.

Filters help to format data and do filtering over the data at  HTML or JavaScript, in HTML pipe | symbol is required and to do the same in JavaScript we have to use $filter service.

Types Of Filters

AngularJs provides in-build filters as well as give the option to create our own filters.
1) Built-In filters
2) Custom Filters

Built-In Filters

1) uppercase
2) lowercase
3) number
4) date
Lets see how they can be used in formatting data in HTML.



Lets see how $filter service can be applied on JavaScript controller to achieve the same what we have seen earlier.


Some more built-in filters

5) filter : Returns new array by selecting subset of items from an existing array, it will take      string,object, or function to select or reject any subset array.

6) json: Convert JavaScript object into json string, mostly used for debugging purpose.

{{{"state":"karnataka","city":"bangalore"} | json}}

7) orderBy: For getting any array in ascending or descending order orderBy filter can be used, it order string alphabetically and numbers numerically.
It takes two parameter, first parameter decides on which column order has to be done and second parameter should be boolean value.If boolean value is true then  sort the data in reverse order.
8) limitTo :Creates a new array or string with limited numbers of elements.


9) currency : Formats number as a currency, helps to display currency symbol, default currency is currency of that locale.We v can also pass our own symbol to display.


Thursday, 22 January 2015

AngularJS Module Lesson 4

Introduction

AngularJS modules are primarily used to order code execution according to dependencies.

AngularJS applications are structured in modules, modules are like namespaces but are not exactly the namespace. we can inject one or many module into some other module multiple modules we can inject to our angular app as an array at the time of bootstrapping. Each module can do it's own work and structured together in a single page application through bootstrapping process.


Difference between Namespace & AngularJs Module

Namespace is a container, inside each namespace we can put classes,structure,enumeration.
AngularJs modules are linking entities, they are just logical containers whose elements are loosely coupled due to this structure they can be injected and used in some other module as well.

See below to understand more.

This linking structure of module reduces coupling and with the help of injection we can use it on some other modules as well.

 A module can depend on:
  a) Another module
and also contains multiple
  a) Directives
  b) Services
  c) Filters
  d) Controllers

Dissecting  Module

To write any module we can use  
angular.module("moduleName",[])

Attach service,controller,filter,directives to module using chaining

Similarly we can link filters and directives to the modules.

Dependency injection in modules.
If you do not have any dependency on some other module still you have to write empty brackets [] while creating modules.
Note:
Syntax for creating module : angular.module("nameOfModule",[]);
Syntax for fetching modules: angular.module("nameOfModule"); fetch already created module.

Your First Module

To bootstrap AngularJS application we need to create a module and assign it to data-ng-app directive, if we only write data-ng-app (i:e not assign anything to it) then angular will bootstrap appllication with it's default modules only.

So if you want that your module also initialize at the time of angular bootstrapping just write
<html data-ng-app="myBootstrappingModule"> </html>

Once you have bootstrap angular with your module,then you can access the constructs which you have linked with that module.



Injecting Dependent Module

If you want some model, service,directive,filter of different module in your application, then you need to inject that module as dependency to your main bootstrapping module, as shown below.



Conclusion
1) Angular modules are logical collection of angular constructs.
2) Modules are not containers like Namespaces, they just create logical links to attach different                constructs.
3) Modules can be injected inside other modules, through injecting array.
4) It is always necessary to give empty array while creating independent module i:e if we are not injecting anything.
5) angular.module("mymodule") is a syntax to fetch module.

Callback Functions In JavaScript

Introduction

If we can pass any executable code as an argument to any function, then that piece of code is called Callback.

If you have come from JQuery background then you have used this approach several times unknowingly.

Digging callback in JQuery

We have use below piece of code many times.Let's dissect it
$(document).ready( function(){
     console.log("I am a callback function");
});

1) Select document object.
2) Call ready function.
3) Inside ready function passing anonymous function as a parameter.

So we can write above code as;

var callback = function(){
   console.log("I am a callback function");
}
$(document).ready(callback);

So we are passing a executable piece of code as callback and that code is a function itself.

JavaScript Functions

In JavaScript functions are first-class objects.

1) Functions are objects in JavaScript.
2) Objects can be used as any other first class objects i:e they can be stored in variable , can be passed as an argument,etc.


How to create callback function

1) Put the callback as last argument.
2) Check the callback, whether it is defined or not.
3) Check  whether callback is a function or not.


Wednesday, 21 January 2015

Event propagation cycle in Javascript

Introduction
In JavaScript events placed a vital role while interaction with DOM, but life cycle of events are much complicated.

Phases in event life cycle
It is divided into two phases
1. Capturing Phase.
2. Bubbling Phase.
Both of phases makes the event to propagate and make a complete life cycle.

Event Flow
When we click on any event on HTML, that event have to start it's travel from HTML tag toward body and traversing all the tag which comes in it's way, but story dosen't ends here. It also have to go back to the starting HTML tag in the opposite direction, this round trip of events across DOM is called as event life cycle.

Suppose click event is fired on any tag inside HTML then that event starts traversing from top to that tag and wherever it encountered with handler for that event it also got fired until it reaches the tag where event was invoked and traverse back toward the HTML tag , but point needs to be noted that either it will fire the capturing events or bubbling events.

This means either the events will be captured or bubbled, but not the both.

Visual Representation



How to get target element
The element from which the event invoked (event triggered) is called "target"
To get the target below JavaScript code is required.
In IE
    event.srcElement

In all w3c comliant browser.
      event.target

For cross browser use it like:
var target = event.srcElement|| event.target;


Capturing & Bubbling

All methods of event handling ignores capturing phase except "addEventListener"
elem.addEventListener( type, handlerphase ) 
type-> Type of event.
handler-> function to handle that event.
phase ->false-> event bubbling(Default Phase) 
phase ->true-> event capturing "IE<9 does not support capturing at all"

If you want to stop event propagation at any point use:
event.cancelBubble=true (For IE) 
event.stopPropagation() (Other browsers)

Below is an example of event capturing, we are passing phase as true for capturing event.("Change phase to false and run the code")





Summary

1.Event propagation consist of event capturing and bubbling.
2.Event capturing is propagation of event from document to the triggered element.
3.Event bubbling is propagation of event from triggered element to upward towards document.
4.Either capturing or bubbling of an event is possible at a time.
5. IE<9 do not support event capturing at all.
6.To cancel any event event.cancelBubble=true (For IE) 
  event.stopPropagation() (Other browsers)

Event Loops in JavaScript (Multiple processing with single thread)


Introduction

In most of the languages for concurrency there are multiple threads, each concurrent process needs to be assigned to each thread and responsibility of the developer is to maintain deadlock, racing condition and all those dirty threading related stuffs among these threads.

Q & A

Q: Then what is different in Javascript?
A: It has only single thread.

Q: ohh! Then how to manage concurrent tasks with a single thread?
A: That is an “Event Loop Model”.

Q: What is an “Event Loop Model”?
A: To understand it first need to know Javascript memory processing model.

Q: That means JavaScript has a concurrency model based on an "event loop"?
A: Yeah!

Q: But how single thread…hmmm getting confused.
A: In JavaScript, almost all I/O is non-blocking. It includes HTTP requests, database operations and disk reads and writes. The single thread of execution asks the runtime to perform an operation, providing a callback function and then moves on to do something else.
When the operation encountered an event, a message is enqueued along with the provided callback function. At some point in the future when main thread complete it’s work the message is dequeued and the callback will be fired.
Q: I am not clear with what you are saying?
A: Ok! First just understand the memory model for the JavaScript.

Memory Model

Let see the below model->

What Fits Where?
Stack: All the function are allocated to stack and once the function complete it’s work and return back, that particular stack frame popped up.

Heap: If we create any object of javascript that object is created on Heap having a link to its function which is in stack frame.

Queue: A JavaScript runtime that contains an event queue, which is a list of events to be processed. The each event is associated with a callback function.
When the “Stack” is empty, event is taken out of the queue and processed.

Understand Processing Model

  1. Add functions to stack.
  2. Run To completion.(Execute stack frames)
  3. Add events to event queue if any event encountered during processing of stack frame functions.
  4. When the main stack become empty.
  5. Create stack for “callback functions” in event queue.
  6. Run to completion for newly created stack.
  7. If any new event found in newly created stack step 3 will be repeated.

Let us analyse execution steps for above example

  1. We call the function Func1(), so it will be put on stack at first position.
  2. While processing Func1() a new method encountered “Func2()”
  3. A new stack frame is created and pushed above Func1() inside stack memory location.
  4. Now Func2() start its execution.
  5. During Func2() execution ,Func2() encountered with first event having a callback function.
  6. Now JS put this event on event Queue with its callback.
  7. Later on one more event is encountered so JS placed it also in event Queue.
  8. Function Func2() execution completed and stack frame for it will be popped out.
  9. Now it will start executing Func1() from where it previously jump out.
  10. Stack frame for Func2() also popped.
  11. After main stack will be empty, event queue events processed and callback functions Func3() and then Func4() are pushed in stack 
  12. First Func3() will be processed and then after Func4() .

Analyse from below snapshot what we have learn so far




Summary

  1. Javascript has only single thread.
  2. To perform concurrency it has Event Loop Model.
  3. It follows Run to completion & Adding Events to Queue.
  4. No dead lock no racing can be encountered.
  5. Just pass all the functions as callback to the event queue.
  6. All the I/O can be async with a single thread.
  7. Overall a never blocking model is attained with only one thread.
  8. Inside setTimeout, time given by us is minimum time to process the request and not the exact time.