There are Anonymous - Is your Function?

With the likes of jQuery you often have the need to create callback functions. These can be anonymous / inline or named functions. Here is quick post to show the syntax differences between the two.

Anonymous

Here is an anonymous or if you prefer inline function. The function isn’t named and we get straight into the action.


$(".anon").click(function(){
	alert('I have no name!');
});

Named

Here a function is named. I called it ‘doSomethingPointless’.


$(".named").click(doSomethingPointless);

function doSomethingPointless(){
	alert('I know who I am!');
}

You can view a demo of this here.

Callbacks with Data

If you are using a piece of jQuery like $.getJSON method then your callback will have a data parameter. This can be handled anonymously or named as well. Anonymously you would do:


    $.getJSON('dickens-books.json', function(data) {
     // to something
    });

… or if you prefer not to be anonymous then:


$(document).ready(function() {
       $.getJSON('dickens-books.json', sortData);

       function sortData(data){
       // to something
      }
  
  });
});

Leave a Comment