Search code examples
javascriptcallbackjquery-callback

Implement a callback function inside a function


Say I have a function like the following.

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I am calling the callback function like this       
   if(callback != null){
       callback();
   }
});

But I want to define this callback function inside the loadXML function. So can I do this as following?

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I have to call the callback function like this, (do I?) which is a 
   // callback parameter to callback function of loadXML
   callback = function(){
       // The callback function implementation goes here
   }
});

Solution

  • Maybe this could help you to understand the nested callbacks mechanism:

    var loadXML;
    var outerCB;
    var innerCB;     
    
    loadXML = function(method, requestString, cb) {
      // pass the innerCB implementation as argument to the outer cb
      if('undefined' !== typeof innerCB) {
        cb(innerCB);
      } else {
        // in case innerCB would not be defined
        cb(function() {
          console.log('hi from anonymous cb')
        });
      }
    };
    
    
    innerCB = function() {
      console.log('hi from innerCB cb!')
    };
    
    outerCB = function(callback) {
      if('undefined' !== typeof callback) {
        callback(); // innerCB();    
      } else {
        console.log('no cb passed, do something else')
      }    
    }
    
    loadXML('Method', 'abcd', outerCB) // hi from innerCB cb!