multiple callback functions in javascript

In my previous post i have explained about what is a callback function. In this post i am going to explain about multiple callback functions in javascript and how to use multiple callback functions.

Using two callback functions


A callback function is a function which is passed as a argument to the other function, and the callback function is "called back" inside that other function. Javascript also provides us to use multiple callbacks functions. We can pass two callback functions as argument to other function and we can call those two callback functions from that functions.

In the following example i am going to show you how we can use two callback functions

Example :


      function successcallBack(successData){
          alert(successData);
      }

      function errorcallBack(errorData){
          alert(errorData);
      }

     function checkNumbers(a,b,callback1,callback2){
          if(a==b)
              callback1('equal');
          else
              callback2('not equal');
     }

      checkNumbers(5,5,successcallBack,errorcallBack);


In the above example we are passing two numbers to "checkNumbers" functions and checking they are equal or not. If both the numbers are equal then we are calling successcallBack function and if the numbers are not equal we are calling errorcallBack function.

In this way you can use multiple callback functions in javascript.

For more posts on javascript visit: javascript


Read more...

CallBack functions in Javascript

After a lot of investigation about callback on many sites, i got some knowledge on what are the callbacks and why we use callbacks. So i just want to share my knowledge here so that it will help some new javascript learners.

What is a callback function


According to wiki "a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time".  Generally a callback function is a function which is passed as a argument to the other function(say FuncA), and the callback function is "called back" inside that other function(FuncA) hance the name callback.

Syntax: 

The following is the syntax for a simple callback function

function multiplier(arg1,arg2,callback)
{
     callback(arg1*arg2);
}

multiplier(2,3,function(result){
   //do something with result
})


In the above example a anonymous function is passed as a callback function to "multiplier" function. Then from that "multiplier" function we have called the callback function.


passing a function as a callback to another function


Generally functions take input in the form of arguments and returns a value using return statement. But using javascript we can do things a little differently. Instead of waiting for a function to complete by returning a value , we can use callbacks to do it asynchronously.(read more about asynchronous programming here: Asynchronous programming). This is more helpful when we are making some Ajax request or Requesting some data from database(which takes some time to finish) etc. Instead of waiting for the call back to be called we can keep on doing other things.

let's see a simple example which uses callback function

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    callback(total);
}

doTotal(90,95,80,function(total){
   var avg= total/3;
   alert(avg);
})


In the above example we have passed a callback function as a argument to doTotal function. The doTotal functions calculates the "total" and calls the callback function by passing "total" to it. Now the callback function uses that "total" to calculate the "average".

Note: Actually we don't need callback in the above example. This can be done by using a regular return statement. Because calculating the sum don't take much time. We mostly use calbacks in the cases where the function takes some time to finish(like ajax requests).


Named callback functions


In the above example we have used anonymous function(function with no name). Now see the same example in which i have used named function as a callback.

function doAverage(total){
     var avg= total/3;
     alert(avg);
}

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    callback(total);
}

doTotal(90,95,80,doAverage);


Make Sure the Callback is a Function


Whenever we are using callback we have to ensure that the value passed as a passback is a function. We can check this by using the below code

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    if(typeof(callback) == 'function')
        callback(total);
     else
       //some other code
}

doTotal(90,95,80,function(total){
   var avg= total/3;
   alert(avg);
})


Here we are testing the callback value using a typeof operator to ensure that whatever is passed is actually a function.

I hope this will give you a basic idea on callbacks.

To read about how to use multiple callbacks visit: multiple callback functions


For more posts on javascript/jquery visit:  javascript/jQuery


Read more...

angular.copy in AngularJS

In this post i am explaining about what is angular.copy or what is the use of angular.copy with example.

recommended readingangularJS tutorial

Consider you have a page in which you are showing list of records on a table and you have a edit form on the same page. When you click on some record then the Edit Form of that field will be displayed.

When you edit some field on the edit form, then it will update the record showing in the table instantly(before clicking update/save) button. This problem arises when you have table(list of records) and Edit form on a single page. As shown in the below picture.



You can solve this issue by using angular.copy.  Instead of binding to a value directly , we can make a deep copy of that object and use it for editing.

Example: 

Consider you have the following html

<html ng-app="app">
<head lang="en">
    <title>Angular copy example</title>
</head>
<body ng-controller="AppCtrl">
    <form>
        <input type="text" ng-model="selectedEmployee.firstName" />
        <button ng-click="saveEmployee(selectedEmployee)">Save</button>
    </form>
    <table>
        <thead>
            <tr>
                <td>FirstName</td>
                <td>LastName</td>
                <td>Email</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="employee in employees" ng-click="selectEmployee(employee)">
                <td>{{employee.firstName}}</td>
                <td>{{employee.lastName}}</td>
                <td>{{employee.phone}}</td>
            </tr>
        </tbody>
    </table>
</body>

</html>

And your javascript will be

var app = angular.module("app", []);

app.controller("AppCtrl", function ($scope) {

    $scope.employees = [
                { "firstName": "Anderson", "lastName": "Brit", "email": "brit@demo.com" },
                { "firstName": "John", "lastName": "Cena", "email": "cena@demo.com" },
                { "firstName": "Andy", "lastName": "Murray", "email": "murray@demo.com" },
                { "firstName": "Chriss", "lastName": "Merry", "email": "merry@demo.com" },
                { "firstName": "Peter", "lastName": "Andrew", "email": "andrew@demo.com" },
                { "firstName": "Loosy", "lastName": "Mally", "email": "mally@demo.com" },
                { "firstName": "John", "lastName": "Goray", "email": "goray@demo.com" }
    ];

    $scope.selectEmployee = function (employee) {
        $scope.selectedEmployee = employee; //model to use in Edit Form
    }

    this.saveEmployee = function (contactToUpdate) {
        $scope.selectedEmployee.firstName = contactToUpdate.FirstName
    }
});


You have a table which is showing the list of records and above the table you have a form through which you can edit the first name of any record. First you have to select the record, the first name of the record will be displayed in the textbox and then you have to edit the name then click on save button , finally it gets saved.

But the problem here is when you start typing in the textbox that will get updated in the table at the same time.

Using angular.copy to solve the issue:

So in order to fix this issue you have to make a copy of the selected employee and you need to pass that object to your Edit Form. This can de done as below

Change your html so that you use the new copied object in Edit Form

<form>
    <input type="text" ng-model="employeeCopy.firstName"/>
    <button ng-click="saveEmployee(employeeCopy)">Save</button>
</form>

Now change your javascript to:

$scope.selectEmployee = function (employee) {

$scope.selectedEmployee = employee;

        $scope.employeeCopy = angular.copy(employee);
    }
    this.saveEmployee = function (employeeCopy) {
        $scope.selectedEmployee.firstName = employeeCopy.firstName;
    }

Now as your table's employee object and Edit form's employee object are different.  It will get updated only after clicking on save button.

This is the use of angular.copy.

Hope it helps.

For more posts on angularjs please refer: AngularJS
Read more...

Getting selected rows from ng-grid AngularJS

In this post you are going to learn how to get the selected rows from ng-grid in AngularJS.

Read our previous posts on ng-grid: ng-grid in AngularJS

If you are using a ng-grid then you may need to get the selected rows. You can do this using selectedItems property.

Based on the ng-grid document(http://angular-ui.github.io/ng-grid/) selectedItems is the property of ng-grid .

Consider you have a ng-grid like below.

<body ng-controller="MyngGridCtrl">
        <div class="ngGridStyle" ng-grid="myGrid">
        </div>
</body>

and your javascript would be

$scope.myData=[{ ID:1, Name:'John',Country:'USA'},
            {ID:2, Name:'Sachin' , Country:'India'},
            { ID:3, Name:'Smith' , Country:'UK'} ];

 //define a array to hold selected rows
$scope.selectedRows=[];

$scope.myGrid={
            data:'myData',
    selectedItems:$scope.selectedRows
};

Now you can use $scope.selectedRows array to show the selected rows like below.

<body ng-controller="MyngGridCtrl">
        <div class="ngGridStyle" ng-grid="myGrid">
<pre>{{selectedRows}}</pre>
        </div>
</body>

Selecting single row in ng-grid:

If you want your users to click on only one row(single row) of ng-grid then you can do it by using  "multiSelect: false" property. By default the multiSelect property will be set to true so that grid allows us to click on more than one row.

To disable multiSelect of ng-grid then change your javascript to

$scope.myGrid={
            data:'myData',
multiSelect:false,
     selectedItems:$scope.selectedRows
};

Now to show the selected value use below code

<body ng-controller="MyngGridCtrl">
        <div class="ngGridStyle" ng-grid="myGrid">
<pre>{{selectedRows}}</pre>
        </div>
</body>

As we are having single record in our $scope.selectedRows array we are using selectedUsers[0] (First record of the array)

In this way you can get the selected rows form ng-grid in AngularJS

Hope it helps you.

For more useful posts on AngularJS visit: AngularJS

Read more...

hide columns in ng-grid AngularJS

In this post you are going to learn how to hide specific columns in ng-grid (or) how to show only specific columns in ng-grid in AngularJS.

Please read my previous post on ng-grid to understand this post easily: ng-grid in AngularJS

Consider you have the following HTML code

<html ng-app="myApp">  
<head>
<title>My ngGrid Demo</title>  
<link rel="stylesheet" type="text/css" href="ng-grid.css" />
<link rel="stylesheet" type="text/css" href="myAppstyle.css" />
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="ng-grid-1.3.2.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="MyngGridCtrl">
<div class="ngGridStyle" ng-grid="myGrid">
</div> 
</body>
</html>

and the required AngularJS code to show the ng-grid is

var myAppRoot = angular.module('myApp', ['ngGrid']);
 
myAppRoot.controller('MyngGridCtrl'function ($scope) {
    $scope.myData = [{ ID: 1, FirstName: 'John', LastName: 'somename', Country: 'USA' },
                   { ID: 2, FirstName: 'Sachin', LastName: 'somename', Country: 'India' },
                  { ID: 3, FirstName: 'Smith', LastName: 'somename', Country: 'UK' }
    ];
 
    $scope.myGrid = { data: 'myData' };
});

But when you use the above code, all the columns in $scope.myData object will be showed in the grid. If you want to show only specific columns then use the following code.

Let us say, you want to show only FirstName and LastName, then change the code of ng-grid like below

$scope.myGrid = {
    data: 'myData',
    columnDefs: [
           { field: 'FirstName', displayName: 'MyFirstName' },
           { field: 'LastName', displayName: 'MyLastName' },
    ]
};

The above code shows only FirstName and LastName columns and hides all the remaining columns.

In this way you can show specific columns in ng-grid. Hope it helps you. 
Read more...

ng-grid in AngularJS

In this article i am going to explain how to use ng-grid in AngularJS , ng-grid example in AngularJS.

Before using ng-grid in AngularJS you have to add the following references.

1.JQuery
2.AngularJS
3.ngGrid's javascript files
4.ngGrid css files

you can download the above references from this link: angular ngGrid

Consider you have the following HTML code

<html ng-app="myApp">  
<head>
<title>My ngGrid Demo</title>  
<link rel="stylesheet" type="text/css" href="ng-grid.css" />
<link rel="stylesheet" type="text/css" href="myAppstyle.css" />
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="ng-grid-1.3.2.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="MyngGridCtrl">
<div class="ngGridStyle" ng-grid="myGrid">
</div> 
</body>
</html>

now add some styles to grid-add following css to your myAppstyle.css

.ngGridStyle {
border: 1px solid black;
width: 200px; 
height: 400px
}

Now add the following code to your app.js file

var myAppRoot = angular.module('myApp', ['ngGrid']); 

myAppRoot.controller('MyngGridCtrl', function($scope) {

//define some object here
$scope.myData=[{ ID:1, Name:'John',Country:'USA'},
{ID:2, Name:'Sachin' , Country:'India'},
{ ID:3, Name:'Smith' , Country:'UK'} ];

//now add the above object to your ngGrid
$scope.myGrid={data:'myData'};
});

Now when you run your code you will see the data in Grid.

To hide specific columns in ng-grid read: hide columns in ng-grid AngularJS

For more articles on AngularJS refer: angularJS 

Read more...

How to redirect a page using JQuery

If you want to redirect from one page to another page when clicking on a button or any other element using JQuery you can do it in the following ways.

You can use

1. window.location.replace("url") or

2. window.location.href = "url"; or

3. $(location).attr('href', url);

Consider you have a button, and when you click on that button, you have to redirect to another page. For this we csn use the below code

<input type="button" id="redirect" value="click to redirect" />

The JQuery code is

1. Using window.location.replace

$(document).ready(function () {
    $("#redirect").click(function () {
    window.location.replace("http://google.com"); //page will redirect to google.com   
 })

2. Using window.location.href

$(document).ready(function () {
      $("#redirect").click(function () {
          window.location.href ="http://google.com";
      })
})

3. Using $(location).attr

 $(document).ready(function () {
        $("#redirect").click(function () {
           var url = "http://google.com"
           $(location).attr('href', url);
         })          
  })

It is better to use window.location.replace than using window.location.href, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

In this way you can redirect from one page to another page using JQuery

Hope it helps you.

read our previous post : Check Given Date Greater than Current Date JavaScript/JQuery

For more posts on JQuery see here : JQuery
Read more...