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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With