添加回调函数 - 总是

问题描述:

我发现自己使用一种奇怪的方式将回调函数添加到我的函数中,我想知道是否有一种更通用的方法来向函数添加回调,最好的情况是我会遇到一种情况,我的所有函数都会检查最后给定的函数作为函数的参数,如果是,则将其用作回调。

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.

这就是我过去的做法:

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!' );
});

有什么建议吗?

如果你真的想,可以使用.cb原型扩展Function.prototype。类似于:

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
}

并且调用会略有变化:

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

只是一个想法。您可以根据需要制作语法。

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