• About
    • asdfasdf
      • ffdsfsdf
  • Portfolio

  • Web Development
  • SEO Techniques
  • Tips and Tricks
  • Site News

Home » Web Development » Javascript Callbacks – Async your site

Javascript Callbacks – Async your site

Posted by: qrpike    Tags:      Posted date:  November 21, 2011  |  No comment



One of the best features of javascript is that its event based and Asynchronous. This means the system will idle until something happens and then execute the desired event. This lets us do very powerful things like very async HTTP requests.

Callbacks are amazing when the code starts getting long and performance is key. Javascript callbacks help us organize our code in a clean way. Also sending functions as a parameter is another good feature of javascript that most languages dont allow.

Example of a callback:

function get_data(url,callback){
     $.getJSON(url,function(data){
           callback(data);
     });
}

get_data('http://example.com/data.json',function(data){
      // This will be called when the getJSON function is done and returns us the data
});

So this code basically calls a HTTP request to get the JSON data, when it returns, it will pass the JSON data back to the callback function.

This lets us build much more object oriented code, and allows us to use functions much more anonymously. For instance the get_data function can be used for any JSON get data call with different callbacks for each case.

You can also pass callbacks:

function get_data(url,callback){
     $.getJSON(url,function(data){
           callback(data);
     });
}

function login(user,pass,callback){
      var url = 'http://example.com/login?u='+user+'&p='+pass;
      get_data(url,callback);
}

login('demo','demo',function(data){
     // This will be executed when the get_data call is completed:
     console.log(data);
});

    Share This
About the author
qrpike



Wanna say something?





  Cancel Reply

« jQuery – Fast selectors using Context
Install LAMP on Amazon EC2 »
  • Recent Posts

    • nginx init.d start script
      #!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig:...
    • Install nginx on CentOS Min.
      First you will need to install a compiler: yum install gcc-c++ Then install the Perc...
    • MYSQL Connection Pool in Node.js
      So, one of the cool advantages of Node.JS (over PHP for example) is the ability to pool...
    • Install FTP and Add User on Amazon EC2
      First we need to install very secure ftp demon yum install vsftpd Once its installed...
    • Install LAMP on Amazon EC2
      If you create a new 64-bit Amazon AMI on their EC2 system, this is the easiest way to get LAMP...



 

 
Copyright © 2010 Peerapong. Remove this once after purchase from the ThemeForest.net