Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding callback to function - always

Tags:

javascript

I found myself using a weird way to add callback functions to my functions and I was wondering if there is a more generic way to add callbacks to functions, best case I would have a situation where all of my functions check the last given param for being a function and if so use it as a callback.

This is how I did it in the past:

var myFunc = function( obj ) {

  if ( arguments.length > 0 ) {
    if ( _.util.typeofObj( arguments[arguments.length-1] ) === Function ) {
      var callback = arguments[arguments.length-1];
    }
  }

  // some code ...

  if ( callback !== undefined ) {
    callback();
  }

};

var foo = myFunc( myObj, function(){
  alert( 'Callback!' );
});

Any suggestions?

like image 923
ezmilhouse Avatar asked Mar 28 '11 20:03

ezmilhouse


1 Answers

I prefer a formal parameter:

var myFunc = function(obj, callback) {
   ...
}

This way it makes it obvious that there is a callback. You also don't have to mess around with the arguments object; you can just check to see if callback is undefined, and then check to see if it is of the appropriate type (Function).

like image 155
Vivin Paliath Avatar answered Nov 03 '22 22:11

Vivin Paliath