Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, November 3, 2015

AngularJS - Best practices

Introduction:
This a quick guide for myself to check/review what pattern/style/standard should be followed during AngularJS application development. Please check the resources section for the links where the gurus have explained elaborately the reason behind each item in this post. Once someone gets the head around the explanations or becomes more advanced developer, this post will serve as a quick cheat sheet for a refresher and reference. Added a facts section which would help going through the practices to understand better.

Some quick facts:
  1. All services (value, factory, service) in AngularJS are Singleton 
  2. Service services are instantiated with the new keyword, need to use this for public methods and variables
  3. Factory services expose it's members (variable, function) using return{} defined in it
Practices grouped by component:

ComponentPractices to follow
Module1 - 11
ControllerModule + (12, 13, 15, 16, 17, 18)
ServiceModule + (14, 19)
DirectiveModule + (20, 21, 22, 23, 24, 25)
RouterModule + (18)


Best practices items:
  1. Create separate file for each controller/service/router/directiveReason: code separation, better testability of code, developers work on independently without being affected by others
  2. File name should follow - ..js
  3. Test file should use spec suffix. ..spec.js
  4. Application Structure should follow LIFT(Locate, Identify, Flat, Try to be DRY) Principle.
    1. Locating our code is easy 
    2. Identify code at a glance 
    3. Flat structure as long as we can 
    4. Try to stay DRY (Don’t Repeat Yourself) or T-DRY
  5. Use unique naming conventions for modules and with separators for sub-modules
    Reason: help avoid module name collisions
  6. Put any member variables in any module on top
    Reason: helps identify instantly what members are defined and used in the implementation flow
  7. Use named functions instead of passing an anonymous function in as a callback. May ideal to use on major functions
    Reason: easy to debug, reduces the amount of nested callback code, increases code readability
  8. Declare any function in any module at the bottom. JavaScript anyway hoists the function definition at the top during execution
    Reason: helps separate the implementation detail from the flow and increases readability
  9. Use functional declaration over functional expression (declare and assign to a var)
    Reason: removes the concern over using a function before it is defined. Code organization (moving a block of code up or down) won't break anything
  10. Use IIFE scoping. Ideal solution should be creating build task to wrap the concatenated files inside an IIFE. IIFE - Immediately Invoked Function Expression.
    Reason:to avoid polluting the global scope with custom function declarations
  11. Consider manual annotation for dependency injection
    Reason: to make the code safe of minification
  12. Use the 'controller as' syntax over the classic $scope. Need to follow below steps for that - 
    1. Use 'controller as' in view (HTML). Like - 'MyController as ctl'
    2. Refer any members using the controller reference. Like - 'ctl.aValue'
    3. In controller, use a capture variable and associate members to the capture variable. Like - 'var vm = this; vm.aValue = 'A Value';'

      Reason
      : 
      avoids any reference issues, gives way to write code on contextual manner, easier to read
  13. Put bindable variables on top
    Reason: helps identify instantly which members of the controller can be bound and used in the View
  14. Put member variables on top
    Reason: helps identify instantly which members can be called and must be unit tested
  15. Defer logic in a controller by delegating to services and factoriesReason: Controller would be slimmer where implementation is hidden. Allows logic to be reused by multiple modules (specially by other controllers) and easier for unit testing
  16. Use one controller per view. If any logic needs to be reused, better to move it to a factory/service and use it from each separate controller
    Reason: Controller will be slimmer, writing unit test will be simpler
  17. Should use prototype to extend a controller and Object.create to create new object
  18. When a controller must be paired with a view and either component may be re-used by other controllers or views, define controllers along with their routes (check this)
  19. Use this for public methods and variables as services are instantiated with the new keyword
  20. Consider creating a directive for any DOM manipulation. If alternative ways can be used such as using CSS to set styles or the animation services, Angular templating, ngShow or ngHide, then use those instead.
    Reason: DOM manipulation can be difficult to test, debug
  21. Use unique and short directive prefix
    Reason: helps identify the directive's context and origin
  22. Use restrict E for standalone element represented by the directive
  23. Use restrict A when the directive is enhancing a DOM element's attribute
  24. Avoid ng- as these are reserved for Angular directives
  25. Directives normalization
    1. Prefer using the dash-delimited format (e.g. ng-bind for ngBind). To use an HTML validating tool, data-prefixed version can be used (e.g. data-ng-bind for ngBind).
    2. Prefer using directives via tag name and attributes over comment and class names.
      Reason: easier to determine what directives a given element matches
  26. Directive creation
    1. Prefer using the definition object over returning a function
    2. prefix own directive names
      Reason: to avoid any future collisions
    3. Unless template is very small, it's typically better to break it apart into its own HTML file and load it with the templateUrl option
  27. Directives should clean up after themselves. Use $element.on('$destroy', ...) or $scope.$on('$destroy', ...) to run a clean-up function when the directive is removed
  28. use controller when want to expose an API to other directives. Otherwise use link.
  29. Use angular wrapper services. Like $document, $window, $timeout, $interval etc. instead of using native.
    Reason: easily testable rather mocking native ones by yourself
Few Additional items: these items are more like personal preference. Though the Angular gurus (John Papa, Todd Motto) are more used to doing these or suggesting to do so.
  1. Consider separate line to inject dependencies rather in-line dependencies
    Reason: long list of dependencies makes it harder to read. Little confusing as last item in the array is a function rather string value
  2. Use ng-annotate for Gulp or Grunt and comment functions that need automated dependency injection using /* @ngInject */.
  3. Tool usage:
    1. Use Jasmine or Mocha for testing
    2. Use protractor for E2E (End to End) testing 
    3. Use karma for test runner
    4. Use Sinon for stubbing and spying
    5. Use headless browser like PhantomJS
    6. Use JSHint as code analyzer 



Resources:
1. https://github.com/johnpapa/angular-styleguide
2. https://github.com/toddmotto/angularjs-styleguide
3. http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
4. http://www.johnpapa.net/angular-function-declarations-function-expressions-and-readable-code/

Sunday, October 18, 2015

Bootstrap - concepts

About bootstrap:

  • Uses HTML, CSS and Javascript
  • front-end framework
  • Easy and faster to use and develop 
  • Responsive design 
  • Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core framework 
  • Browser compatible 


Bootstrap concepts:


  1. Application setup with bootstrap 
    1. Reference to bootstrap
      1. Download - http://getbootstrap.com
      2. CDN - 
        1. CSS - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css
        2. JavaScript - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
    2.  <!DOCTYPE html> at the beginning of the html page
    3. Mobile first settings - '' 
      1. Width is the width application should take to display
      2. initial-scale - initial zoom of the page
    4. Container - bootstrap requires a containing element to wrap site contents. There are two container classes to choose from - 
      1. .container - class provides a responsive fixed width container
      2. .container-fluid class provides a full width container
         
  2. Bootstrap Grid System - grid systems are used for creating page layouts through a series of rows and columns that host application content
    1. Rows must be placed within a .container class
    2. Content should be placed within the columns, and only columns may be the immediate children of rows
    3. Predefined grid classes
      1. .row
      2. .col-xs-<#> .col-sm-<#> .col-md-<#> .col-lg-<#> - # could be 1-12
    4. Multiple column classes can be used to support wide range of devices  
  3. Normalize - bootstrap uses Normalize to establish cross browser consistency in the default styling of HTML elements. Normalize.css is a modern, HTML5-ready alternative to CSS resets. CSS reset is to set styling to html elements to null thus avoiding cross-browser differences as much as possible
     
  4. Text emphasis - text-left text-center text-right text-muted text-primary text-success text-info text-warning text-danger.
     
  5. List - list-unstyled list-inline.
     
  6.  Bootstrap tables - 
    1. base table markup - table 
    2. Optional markups - table-striped table-bordered table-hover.(example) 
    3. Contextual classes - active success warning danger. (example)
    4. The .table-responsive class creates a responsive table. Put this class in a div which holds a table
       
  7. Bootstrap form layouts- 
    1. Types
      1. Vertical (default) form 
      2. In-line form 
      3. Horizontal form
    2. Rules to follow 
      1. improve accessibility - always use >form role="form"< 
      2. optimum spacing - wrap labels and form controls in >div class="form-group"< 
      3. class .form-control to all textual input, textarea and select elements
      4. For Horizontal form - 
        1. Add class .form-horizontal to the
          element 
        2. Add class .control-label to all
        3. Use grid classes to align labels and groups of form controls
    3. Example - includes all three type of forms  
  8. Alert - 
    1. Create an alert 
      1. Use .alert class in a div
      2. Followed by one of four contextual classes .alert-success, .alert-info, .alert-warning or .alert-danger.
    2. To add close functionality
      1. Add a link or button element in alert div
      2. add class="close" and data-dismiss="alert".
      3. Use × (×) HTML entity for close buttons
    3. Animated alert - add class fade in in alert div.
       
  9. Dropdown - (example)
    1. To create
      1. Mark a div with class="dropdown".
      2. Add a button or link to open dropdown menu with "class=dropdown-toggle" and data-target="dropdown".
      3. Add class="caret" in a span element to show dropdown arrow
      4. Add class="dropdown-menu".
    2. Dropdown divider - class="divider" in li element
    3. Dropdown header- class="dropdown-header" in li element
    4. Make it accessible to screen readers
      1. Add role="menu" and aria-labelledby="aName" in ul element
      2. Add role="presentation" in li element
      3. Add role="menuitem" in HTML element used inside li
  10. Panel
    1. Create with .panel class in a div
    2. need to define panel-header panel-body panel-footer
    3. Contextual classes - panel-default panel-success panel-info panel-danger panel-warning panel-primary.
    4. To group panels - panel-group.
  11. Collapsible
    1. On button or link
      1. Create a div with collapse class
      2. Create a link or button HTML element with data-toggle="collapse" and data-target="#div_id". This is to show/hide the collapsible div
    2. On a panel - (example)
      1. Add button or link in panel header (see above)
      2. Put panel body and footer in a div with classes panel-collapse collapse.
    3. Accordion - (example)
      1. Panel group div should be ided with a name
      2. Use the data-parent attribute to specify the div id - all collapsible elements under the specified parent will be closed when one of the collapsible item is shown
         
  12. Tabs
    1. Tabs are created with $gt;ul class="nav nav-tabs"<.
    2. Current page is marked using class="active" in li element
    3. Use dropdown creation structure in a li which needs to be displayed as dropdown and mark that li with class="dropdown". (example)
    4. dynamic tabs
      1. add the data-toggle="tab" attribute to each link
      2. add a .tab-pane class with a unique ID for every tab
      3. wrap them inside a div element with class .tab-content. 
    5. Pills - similar concept as tab. Most cases replacing tab with pill will work
  13. Modal - (example)
    1. Use a button or a link with attributes: 
      1. data-toggle="modal" opens the modal window 
      2. data-target="#id" points to the id of the modal
    2. Defining modal 
      1. The parent div of the modal must have an ID, will be used in data-target attribute and .modal class 
      2. The attribute role="dialog" to improve accessibility 
      3. The .modal-dialog class sets the proper width and margin of the modal. 
    3. Defining modal content
      1. A div with class="modal-content" 
      2. Add the modal's header .modal-header, body .modal-body, and footer .modal-footer. 
      3. To add close feature in header
        1. Add a button/link inside the header with data-dismiss="modal"
        2. Add .close class styles the close button
      4. Add .modal-title class styles the header with a proper line-height.
  14. Images - below classes need to use in img html element
    1. img-rounded img-thumnail img-circle img-responsive.
       
Note:
1. To learn about bootstrap elements which are not mentioned and know more in detail about the elements explained, see the resources



Resources:
1. http://www.w3schools.com/bootstrap/
2. http://www.tutorialspoint.com/bootstrap/

Saturday, October 17, 2015

JQuery - Handout - quick memory refresher

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.

About jQuery:

1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming


jQuery concepts:

  1. Pointing to jQuery
    • From local reference - ''- assuming jquery.js file is in same folder with the html
    • Content Delivery Network (CDN) based - 'src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"'
       
  2. launching code - Option-02 is prepared as that's invoked as soon as the DOM is ready rather waiting the page loaded fully (including images)
    1. Option-01: window.onload = function() { //code};
    2. Option-02: $( document ).ready(function() { //code });
    3. Option-03: is shortcut to option-02. '$(function(){ //code});'
       
  3. Callbacks and functions - A callback is a function that is passed as argument to another function and will be executed only after the function where it's passed has completed
    1. Callback without Arguments - '$.get('aPage.html', callBackFn);'
    2. Callback with Arguments - 
      1. Not possible - '$.get('aPage.html', callBackFn(param1, param2));'. This will execute the callBackFn first and return of it will be passed to get function
      2. Correct way - '$.get( "aPage.html", function() { callBackFn( param1, param2 ); });'
         
  4. $ vs $()
    1. Methods called on jQuery selections (used $()) are in the $.fn namespace, and automatically receive and return the selection as this
    2. Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments
        
  5. Ways to avoid conflict with other libraries
    1. new alias - noConflict returns a reference to jQuery function
      'var $j = jQuery.noConflict();'
    2. use self invoking function -
      'jQuery.noConflict();(function($){ //code})(jQuery);'
    3. Argument through jQuery(document).ready() function
      'jQuery(document).ready(function( $ ) { // code });'
       
  6. Selecting elements
    1. by 
      1. tag name - '$("aDOM");'
      2. ID - '$("#idToFind");'
      3. class name - '$(".className");'
    2. Pseudo selectors - :visible :enabled :checked :text :button :file (see references for complete list)
    3. comma to use to select multiple DOM objects
    4. chaining - any method call on a selection returning a jQuery object, allows to call jQuery method on the object without pausing for a semicolon.
      '("#aDiv").find("p").eq("1").html("Changed text");' - find second p in a dive called aDiv and change content
       
  7. Methods - 
    1. getter/setter - html, text, val - can be both setter (with argument) or getter (no argument) 
    2. Move, copy and remove elements
    3. Attributes - .attr() to get/set value to selector's attribute.
      1. Object of key-value pair can be passed to set multiple
         
  8. Selection traversing
    1. parents - .parent() .parents() .parentUntil() .closest(). 
    2. children - .children() .find().
    3. Siblings - .prev() .next() .siblings() .nextAll() .prevAll() .nextUnti() .prevUntil()
    4. Styling and dimensions
    5. CSS classes - addClass("aClass") removeClass("aClass").
    6. Dimensions - width, height - getter/setter
        
  9. Data methods - stores data to the element and manages the memory issues.
    '$("#aDiv").data("aKey", {name:"Riaz"});' '$("#aDiv").data("aKey");'
      
  10. Utility methods - 
    1. $.trim() - 
    2. $.each() - generic iterator function for looping over object/arrays/ array-like objects
      example:
      '$.each([1,2,3,4], function(idx, val){ console.log("Element "+idx + " is "+val);});'
      output:
      Element 0 is 1
      Element 1 is 2
      Element 2 is 3
      Element 3 is 4
       
    3. $.proxy(function, scopeObj) -
      example:
      var aFn = function() { console.log( this ); };
      var aObj = { name: "Riaz" };
      aFn();
      var proxyAFn = $.proxy( aFn, aObj );
      myProxyFunction();

      Output:
      Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…}
      Object {name: "Riaz"}
       
    4. $.type() - returns the type of passed object
    5. .map() - returns array from matched elements from selector
        
  11. jQuery events - 
    1. Some common events
    2. Mouse Event Key Event Form Event window Event
      click keypress submit load
      dblclick keydown change unload
      mouseenter keyup focus size
      mouseleave    blur scroll
    • Event call syntax - 
      • Assign an event - $("p").click();
      • Indicates what should happen after event -
        $("p").click(function(){ /*actions*/});
    • Usage of '.on()'. 
      • All the methods above are shortcut of this
      • Syntax - '$("p").on("click", function(){/*actions*/});'
    • Handling event - 
      • Many events single event handler - comma separated events
      • Multiple event and event handler association -'$( "p" ).on({ "click": function() { console.log( "clicked!" ); },
        "mouseover": function() { console.log( "hovered!" ); } });
        '
      • Data can be passed to event -
        '.on( "click", {name:"Riaz"}, function(event){ console.log("Name:"+event.data.name");});'
    • Instead of anonymous function, a named function can be passed as event handler 
    • Namespacing event - for complex and plugin application, it's a good idea to namespace application specific events to avoid conflict 
    • tead down events
      • Unbind all click event - $( "p" ).off( "click" ); 
      • Unbind only aHandler from click - $( "p" ).off( "click", aHandler );
    • Event handler to run only once - using '.one(...)'
    • Properties and method of eventhanlder
      • Properties - pageX pageY which type data target namespace timestamp etc.
      • Methods - preventDefault() stopPropagation() etc
12. Ajax in jQuery
  • Syntax - '$.ajax(...)'
  • Data types - type of data you expect to get back from an Ajax request
    • text html script json jsonp xml
  • API -
    // Using the core $.ajax() method
    $.ajax({
    // The URL for the request
    url: "- page url",
    // The data to send (will be converted to a query string)
    data: {  },
    // Whether this is a POST or GET request
    type: "GET",
    // The type of data we expect back
    dataType : "json",
    // Code to run if the request succeeds;
    success: function( json ) { /* do something */ },
    // Code to run if fails; raw request and status codes are passed
    error: function( xhr, status, errorThrown ) { /* do something */ },
    // Code to run regardless of success or failure
    complete: function( xhr, status ) { /* do something */ } });
  • Convenient functions - below functions are wrapper around core .ajax()
    • functions - $.get $.post $.getScript $.getJSON
    • parameters - 
      • Required - url
      • Optional - data success dataType
  • Ajax events
    • Local events - specify within ajax request object
      • beforeSend success error complete
    • Global events
      • ajaxtStart ajaxStop
13. Serializing form data
  • Using $("#aForm").serialize() - serializes form data into a query string
  • Using  $("#aForm").serializeArray() - serializes to array of objects

Resources:
1. http://api.jquery.com/
2. http://www.w3schools.com/jquery/
3. https://learn.jquery.com/

    Thursday, October 1, 2015

    JavaScript - Karma - Setup - prepare the environment to work with karma

    Introduction:
    This article covers how to setup karma and run a sample test to make sure installation worked without any issues. Both local and global installation will be covered. Karma installation depends on some other dependent technologies which are not part of this article. 

    Brief introduction about the technologies involved:

    Node:
    • Considered as server side JavaScript or browser less JavaScript
    • JavaScript runtime built on Chrome’s V8 JavaScript engine
    • Node uses event driven, non-blocking I/O model which makes it lightweight and efficient

    npm:
    • This is a package manager for JavaScript is default for Node.js
    • Elaboration is 'Node.js Package Manager'

    karma:
    • Test Runner tool for JavaScript invented by AngularJS team 
    • Karma runs on Node.js and is available as an NPM package
    • Test runner means way to run jasmine/mocha (Javascript unit test tool) without loading explicitly in the browser. To confuse thing, it's testing without the browser in the browser. 

    Karma setup:
    Karma installation needs node and npm installed prior. So those two installation will be covered first. 

    Environment info:
    • Operating system - Windows 2008 R2
    • node version - 4.1.0
    • npm version - 3.3.3

    1. Setup node:
    • Link to download: https://nodejs.org/en/
    • Click on download button which will download file ‘node-v4.1.0-x64.msi’
    • Execute the msi file. Setup wizard is simple enough, just click on Next button
    • It will install command prompt and node.js, both are shell/command prompt. Node.js is used for node programming.
    • Test installation’s done successfully. Use command prompt. Run ‘node –v’. returned 4.1.0.

    2. Update npm: 
    • Node is bundled with a version of npm. However, npm gets updated more frequently than Node does, so it’s a good idea to upgrade npm. Before upgrading npm, run ‘npm -v’ which returned ‘2.14.3’.
    • Install npm – execute command ‘npm install npm -g’ in ‘node command prompt’
    • Check upgraded version. Execute ‘npm -v’ which returned 3.3.3.

    3. Install karma:
    Karma can be installed per project or in global context accessible for each project. 

    Local installation:
    • Go to the folder where karma needs to be installed
    • Execute command 'npm install karma' from 'node.js command prompt
    • This will create a folder called 'node_modules'. Actually installing any npm package will create that folder where all the dependent modules will be installed
    Global installation:
    • Execute command 'npm install karma -g' from 'node.js command prompt. -g argument indicates installation in global space. 
    • The 'node_modules' will be created in the user's directory.

    4. Install dependencies: 
    Karma requires to install test tool, browser launcher etc. Below commands will add all the dependencies need to run the karma locally. Just add -g to install globally.  

    - 'npm install karma-jasmine --save-dev'
    - 'npm install karma-requirejs --save-dev'
    - 'npm install karma-phantomjs-launcher --save-dev'
    - 'npm install karma-chrome-launcher --save-dev'


    5. Initialize karma:
    • Command: 'node node_modules/karma/bin/karma init'. This will ask series of questions.
    • Testing framework - default jasmine. Use up or down arrow keys to select preferred one
    • Need requireJS - default no. Up arrow to select yes. I use requireJS and all my posts will be referring it
    • Select Browser - default Chrome. Can select multiple in next line. To go to next option, needs to hit double Enter
    • Next needs to specify all source file locations. Double enter for next option
    • Exclude files. 
    • Bootstrap file for requireJS. Selecting yes will create a test-main.js in root location with RequireJS configured and run the tests. Selected no for the purpose of this post.
    • Watch file modification. Select yes. This streamlines any changes in source files and testing done immediately
    • Initialization is done. This will create a file 'karma.conf.js' in the root location where all the above settings can be seen and modified based on need.

    6. Run karma:
    • Command - 'node node_modules/karma/bin/karma start'
    • This will start karma on default port 9876 (if not changed) which will start Chrome browser for it's purpose.

    Notes:

    1. Error-01: Not so obvious error during global karma installation
    Solution: use command -
    - 'npm install --ignore-script -g karma'

    2. Error-02: throw error('No provider for "' + name + '"!');
    Solution: next line of above should display which provider is missing. Install that provider using 'npm install --save-dev'


    Resources:
    1. http://karma-runner.github.io/0.13/intro/installation.html
    2. 



    Friday, September 25, 2015

    Hand out - Javascript - Regular Expression

    Introduction:
    This post is to know regular expression, see usage in sample examples using JavaScript. Plan is to update this post every time a regular expression is solved. Considering this as a quick hand out to refresh memories as well as a list regular expression which are encountered at some point of development life time.


    What is regular expression:
    A regular expression is a sequence of characters that forms a search pattern to match a combination in strings. In JavaScript regular expression is an object which can be created explicitly or implicitly.

    Regular expression creation: 

    Option-01: implicit way -

    var regExp = /[0-9]/;

    Option-02: explicit way- 

    var regExp = new RegExp('[0-9]');

    Note: better to use option-01 as option-02 has implication on execution speed.


    Various patterns:

    1. Direct match - /direct/. This pattern will find a match in string 'Looking for a direct match' but not in 'Misspelled the word diract'.

    2. Special characters - 

    PatternMeaning/exampleMatching StringNon matching string
    \Escape character

    ^matches beginning of input. /^A/ AppleBanana
    $matches end of input. /a$/Bananaapple
    *matches preceding expression 0 or many times. /p*/- Apple
    - Orange
    +matches preceding expression 1 or many times. /p+/- Apple
    - Peach
    - Orange, any string not have p in it
    ?matches preceding expression 0 or 1 times. /p?/- Peach
    - Pear
    - Apple
    - 
    ()matches and remembers it. Also called capturing parentheses. /(p)/
    Table Cell
    (?:)Matches 'x' but does not remember the match

    (?=)Look ahead. /A(?=p)/. Match only if A (capital) followed by p. - Apple
    - Apricot
    - Avocado
    - apple
    (?!)negated look ahead. /A(?!p)/. Match only if A (capital) doesn't follow by p. - Avocado
    - apple
    - Apple
    - Apricot
     |matches either one. /A|a/.- Apple
    - apple
    - one
    - Two
    - Three
    {}matches exactly that many occurrences. /p{2}/. Has to be positive number.- Apple
    - Pepper 
    - Apricot
    - Pear
    - Peach
    { , }matches at least first and at most second. /p{1,2}/.- Apple
    - Pepper
    - Apricot
    - Pear
    - Peach
    []Character set. /[Pe|pe]/.- Pepper
    - Pear
    - Peach
    - Apricot
    - Apple
    [^ ]Negated character set. /[^pe]/.- Pear
    - Peach
    - Apple
    - Apricot
    - Pepper
    \bmatches word boundary where word character not preceded or followed wit any character. /\bp/. - pear
    - peach
    -Apple
    \dmatches digit character. /\d/. equals to /[0-9]/.- 2apples
    - 3 Pears
    - Apple
    - Pear
    \Dmatch non digit character. /\D/. equals to /[^0-9]/.- Apple
    - Pear
    - 2apples
    - 3 Pears
    \smatches white space. /\s/.- 2 Apples
    - Apple or orange
    - AppleOrOrange
    - PearAndPeach
    \Smatches a single character other than white space. /\S/.

    \wmatches any alphanumeric words including _. /\w/. equals to /[A-Za-z0-9_]/.- &^%$A
    match A

    \WMatches any non-word character. /\W/. equals to /[^A-Za-z0-9_]/.- Appl#
    matches #

    Note: the list is not complete. Check Resource links for complete list


    Regular Expression properties:

    Property Name Description
    lastIndexThe index at which to start the next match
    ignoreCaseIndicates if the "i" flag was used to ignore case. Returns true or false
    globalIndicates if the "g" flag was used for global match. Returns true or false
    multilineIndicates if the "m" flag was used match from multiple lines. Returns true or false
    sourceReturns the pattern used in regular expression
    splitThis method is in String. If match found, returns array of substrings.


    Methods related to regular expression:
    Method Name Description
    execthat executes a search for a match in a string. It returns an array
    re.exec(str) - matches the regular expression (re) against the input parameter string (str).

    Properties:
    [0] - The full string of characters matched

    [1], ...[n ] - matched substrings
    index - zero based, index of matched string
    input - the string match happening against
    testtests for a match in a string and returns true or false
    re.test(str) - regular expression (re), input parameter string (str). 

    matchThis method is in String. Executes a search and returns an array of information or null on a mismatch
    str.match(re) - regular expression (re) pattern to match on string (str).



    searchThis method is in String. Returns the index if match found, else -1.
    str.search(re) - regular expression (re) pattern to search from string (str).

    replaceThis method is in String. Replaces matched substring with replacement substring.
    str.replace(re, newSubStr) - replace substring from string (str) if match found based on regular expression (re) pattern with new sub string (newSubStr).

    Note: a function can be used instead of newSubStr as replacement

    splitThis method is in String. If match found, returns array of substrings.
    str.split([separator[, limit]]) - Splits the string (str) based on separator. Limit value can be specified which is optional. If used, it splits on every match on separator but truncates the array to meet the limit.


    Regular expression with flags:

    Syntax: /regular expression/flag;
    Flags:

    i - case ignore search

    g - global search

    m - multi line search


    Examples
    :


    1. Replace all instances of e or E in a String - /e|E/g.

    2. 




    Resources:
    1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
    2. 

    Friday, September 18, 2015

    Hand out - Javascript - requireJS - part-01

    What is RequireJS?
    RequireJS is a module loader for JavaScript which facilitate module based programming where large application is broken down into relatively small and manageable code blocks. That leads to the problem of managing those dependencies between modules and emerges the need of module loader. RequireJS is one of the most popular. It improves script load speed.


    Few concepts:

    1. Without RequireJS, html file has to have all the dependent scripts loaded using script tag and the correct order has to be maintained. That is treated as synchronous loading and scripts will be loaded one at a time which slows the page view. RequireJS uses AMD (Asynchronous Module Definition) where modules are loaded in parallel and boosts the page load


    2. Using require() vs. define()
    Both require() and define() to load dependencies. The require() function is used to run immediate functionalities, while define() is used to define modules for use in multiple locations. In the example, in both app.js and main.js, need to run immediately. So, require() was used. Check the code below to get better understanding. 

    3. In the example, in all places where require() is used, can be replaced with requirejs or vice versa.

    4. In main.js, define() could be used instead of require().


    Use RequireJS - integrate jQuery/bootstrap and print hello world in console


    1. Folder structure - this folder structure is not that important to test RequireJS as long as references are pointed correctly. But have good folder structure helps organizing the files, improves manageability. Folder structure followed -




    css - for css files
    fonts - for fonts
    img - for images 
    js - any JavaScript 
    js/app - will have application specific js files
    js/vendors - any third party js (like - jQuery, bootstrap etc.)
    app.js - contains RequireJS configuration
    main.js - contains the web app dependencies and once loaded can start application using any framework
    index.html - to load the script

    note: app.js and main.js can be combined into one and point from script in html file

    2. Download RequireJS and put in js/vendors folder

    3. Define RequireJS script in the html


    Explanation:
    - only one script tag where src refers to RequireJS. data-main attribute tells require.js to load js/app.js after require.js loads. js extension is not needed as RequireJS works only on JavaScript

    4. Configure RequireJS to load dependecies (jQuery/bootstrap)


    Explanation:

    baseUrl - the root path to use for all module lookups
    paths - path mappings for module names not found directly under baseUrl. The path settings are assumed to be relative to baseUrl, unless the paths setting starts with a "/" or has a URL protocol in it ("like http:")
    shim - Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies

    End of the file, it makes call to main.js using require() function

    5.  Load application dependencies

















    Explanation: 
    - application code requires jQuery. 
    - require method - takes two parameters. First parameter takes dependency array. Second parameter defines the function which have application code. In this case just printing a message to screen.

    6. Open the index.html file in the browser. Used chrome to view it and developer tool to check console message



    Resources:
    1. http://requirejs.org/
    2. http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/