Thursday, May 26, 2016

JQUERY



Conman javascript template structure 

module Admin.Event.TicketInformation {

    var ticketInfo =  (() => {

        var apiCalls = {
            getInfo: () => {},
           addInfo:(e?)=>{}
        }
     function addInfo(e){
     
          apiCalls.addInfo(e).done((e)=>{
                alert('done');
            });
    }

        return {

            init: () => {
               
                $('#btnClick').on('click',this,addInfo);  
            }

        }

    })();
    $(ticketInfo);
}


Query String

 $.QueryString["id"]

Event methods
  

  1. live('click dblClick',data,callBack); < 1.7
  2. bind('click dblclick',data,callBack); < 1.7
  3. on('click dblclick',data,callback);
  4. one('click dblclick',data,callback);
  5. $(selector).click(callback);
  6. off()/ off('click'); // unbind all or specific event
  7. unbind() / unbine('click') // unbind all or specific event
  8. die() // no longer use < 1.7



 Ajax method


  1. $.ajax({});
  2. $.getJson({}); specialize for json
  3. $.get({});// specialize for get
  4. $.post({});// specialize for post
  5. $('selector').load(url,data,callback); get data and innerhtml (for get method)
Traversing Methods




Quary string append to the url 


 var quaryString = { facilityId: facilityId, st: startTime, et: endTime, f: ((isFullDay == "true") ? "1" : "0"), mode: "sv", callback: "" };

                     var q = '/facility/info?' + $.param(quaryString);

$(location).attr('href', '/admin/facility/details');

-------------

moment Date Time Formatter

moment.utc(e.insertedTime).format('MMMM Do YYYY')

Kendo ui currency formater

kendo.toString(e.total, 'c2')

/////////////////////////////////////////////////////////////////
Call Back function

function what wait prevois function is over


defined call back function example

http://www.w3schools.com/jquery/jquery_callback.asp

$("button").click(function(){
    $("p").hide("slow"function(){
        alert("The paragraph is now hidden");
    });
});

after call end in slow , show the alert.
the alert wait for hide function over.
-------------


// define our function with the callback argument
02function some_function(arg1, arg2, callback) {
03    // this generates a random number between
04    // arg1 and arg2
05    var my_number = Math.ceil(Math.random() *
06        (arg1 - arg2) + arg2);
07    // then we're done, so we'll call the callback and
08    // pass our result
09    callback(my_number);
10}
11// call the function
12some_function(5, 15, function(num) {
13    // this anonymous function will run when the
14    // callback is called
15    console.log("callback called! " + num);
16});

--------------------

call back function with ajax


function some_function2(url, callback) {
02    var httpRequest; // create our XMLHttpRequest object
03    if (window.XMLHttpRequest) {
04        httpRequest = new XMLHttpRequest();
05    else if (window.ActiveXObject) {
06        // Internet Explorer is stupid
07        httpRequest = new
08            ActiveXObject("Microsoft.XMLHTTP");
09    }
10
11    httpRequest.onreadystatechange = function() {
12        // inline function to check the status
13        // of our request
14        // this is called on every state change
15        if (httpRequest.readyState === 4 &amp;&amp;
16                httpRequest.status === 200) {
17            callback.call(httpRequest.responseXML);
18            // call the callback function
19        }
20    };
21    httpRequest.open('GET', url);
22    httpRequest.send();
23}
24// call the function
25some_function2("text.xml"function() {
26    console.log(this);
27});

------------------------

call back function are async

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide(10000, function(){
            alert("The paragraph is now hidden");
        });
    });
});
</script>
</head>
<body>

<button>Hide</button>
<input type='button' value='click me' onclick='alert("hi")'/>

<p>This is a paragraph with little content.</p>

----------
   <script>

        let index = 0;
        function some_function(arg1,callback) {

            index = arg1;
            for (var i = 0 ; i < 10; i++) {
                setTimeout(stopTimer, 50000);
            }

            callback();
           
        }

        function stopTimer() {
            console.log(index);
            index++;
        }


        some_function(10,function(){
            alert('over');

        });   


//////////////////////////////////
Plugin 
/////////////////////////////////////


jQuery.center.js  (plugin)


jQuery.fn.center = function(){


var element = this;

changeCss();

$(window).bind('resize',function(){

changeCss();
});

function changeCss(){
var imageHeight = $(element).height();
var imageWidth = $(element).width();
var windowHeight = $(window).height();
var windowWidth = $(window).width();

$(element).css({
    "position" : "absolute",
    "left" : windowWidth/2 - imageWidth/2,
     "top" : windowHeight/2 - imageHeight/2

});
}
}
===========================


html Page


<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="jqery.center.js"></script>
</head>
<body>

    <img src="http://www.wp-tutorials.com/wp-content/uploads/2016/01/jquery-logo.png" width="500px" height="500px">
<Script>

$(function(){

$('img').center();
});

</Script>


</body>

</html>




//////////////////////////////////////////////////////////

Best Practices

////////////////////

01) Load js dynamically

$.getScript( "scripts/gallery.js", callback);


02) cache jquary object

var $element = $('btnClick');
$element.css({font-size:'bold',backgound-color:});
$element.on('click',()=>{});



03) Limit Derect Dom Manipulation


var arr = [];
for(var x=0;x<1000;x++){

arr.push('<li> item '+x+'</li>')
}

$element.append(arr.join(''));



04) User for loop instead of $.each() // native always speed than jquary


check element before oparation.

if($element.length){
$element.on('click',()=>{alert('hi');});
}



05) after function execute, return false.


$('btnClick').click(()=>{
alert('this is button click event');
return false;
});



06) Ajax


use promises

01)

function getPerson(item:any){
return $.ajax({
url :'/api/getPersons',
data: item,
method : 'get',
type :'json'
});
}

getPerson(1).done((e)=>{});

02).

function getPerson(item:number){
return $.ajax({});
}

function getEmployees(item:number){

return $.ajax({});
}

var arr = [getEmployee(1),getPerson(2),getEmployee(3)];

$.when.apply(this,arr).then((ee)=>{

});


03)
when($.ajax({action:'get',url:'/api/getPerson'})).then((e)=>{ alert(e); }).

04) use promise exapmle 2

function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    return $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData
    });
  }

  getName("2342342").done(function(data) {
    // Updates the UI based the ajax result
    $(".person-name").text(data.name); 
  });




do not use like .

function getName(personid) {
    var dynamicData = {};
    dynamicData["id"] = personID;
    $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData,
      success: function(data) {
        // Updates the UI based the ajax result
        $(".person-name").text(data.name);  
      }
    });
  }

  getName("2342342");

07) Event Delegation

var $btnSave = $('#btnSave');
$btnSave.on('click',save);

function save(){ alert('saved');}

08) Optimized Selection

$('#divLogin').find('input:button[name="login"]');

09) Ready

$(init);

function init(){}

10) append attributes / css

$element.attr({ class:'btn btn-primary', value:'click me', id :'btnClickMe'   });


11) To long string manipulation.

do not use string.concat() / use array.join()

12) Use Html5 Data attribute

Example
<input type='button' data-anyKey = 'value' />

example :
<div id="demo" data-role="demo-page" data-value="111" data-options='{"name":"Walter John"}'></div>
use from javascript

$("#demo").data("role");    // "demo-page"
$("#demo").data("value");    // 111
$("#demo").data("options").name;    // "Walter John";
13 Do Chaining

$element.css().bind().off();













No comments:

Post a Comment

Sql server row level policy