JavaScript style for optional callbacks

2019-01-10 06:01发布

I have some functions which occasionally (not always) will receive a callback and run it. Is checking if the callback is defined/function a good style or is there a better way?

Example:

function save (callback){
   .....do stuff......
   if(typeof callback !== 'undefined'){
     callback();
   };
};

10条回答
家丑人穷心不美
2楼-- · 2019-01-10 06:33

I got so tired of seeing that same snippet over and over I wrote this:

  var cb = function(g) {
    if (g) {
      var args = Array.prototype.slice.call(arguments); 
      args.shift(); 
      g.apply(null, args); 
    }
  };

I've got hundred of functions doing things like

  cb(callback, { error : null }, [0, 3, 5], true);

or whatever...

I'm skeptical of the whole "make sure it's function" strategy. The only legitimate values are a function or falsy. If someone passes in a non-zero number or a non-empty string, what are you going to do? How does ignoring the problem solve it?

查看更多
Animai°情兽
3楼-- · 2019-01-10 06:37

You can also do:

var noop = function(){}; // do nothing.

function save (callback){
   callback = callback || noop;
   .....do stuff......
};

It's specially useful if you happen to use the callback in a few places.

Additionally if you are using jQuery, you already have a function like that, it's called $.noop

查看更多
爷的心禁止访问
4楼-- · 2019-01-10 06:38

It can easilly be done with ArgueJS:

function save (){
  arguments = __({callback: [Function]})
.....do stuff......
  if(arguments.callback){
    callback();
  };
};
查看更多
聊天终结者
5楼-- · 2019-01-10 06:39

I have sinced moved to coffee-script and found default arguments is a nice way to solve this problem

doSomething = (arg1, arg2, callback = ()->)->
    callback()
查看更多
登录 后发表回答