7

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?

3 Answers 3

13

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).

Sign up to request clarification or add additional context in comments.

3 Comments

after using the prototype solution for a few weeks now, I switched to your advice, it's just easier to read, find it to be a very important eyecatcher
@ezmilhouse yes, there's less "magic" happening because the formal parameter is obvious :)
@ezmilhouse I suggest changing the accepted answer since you mentioned that you changed your approach.
5

You could, if you really want to, extend Function.prototype with a .cb prototype. Something like:

Function.prototype.cb = function(cb){
   var self = this;
   return function(){
      self.callback = cb || function(){};
      self.apply(self, arguments);
   }
}

then your code would compress to:

var myFunc = function(obj){
   // some code

   this.callback(); // callback will always be defined
}

and the call would slightly change:

myFunc.cb(function(){
   // callback code
})(myObj);

Just an idea. You can make the syntax pretty much whatever you want.

1 Comment

In this case it might not matter much, however, might want to avoid using self since it's a global (yet not reserved) variable.
5

Not sure what you are trying to do here, but a way to add a callback that seems more straight forward:

function( obj, callback ) {
   if(callback) {
      callback();
   }
}

2 Comments

Or to cause some head-scratching, abbreviate as callback && callback()
@Jackob: typeof callback == "function" && callback() is cleaner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.