JQUERY functions with named callbacks

0

I would like to create a function with Jquery so that I could only pass the callback name and function specification, as well as the $ .ajax function, which as an example, I do:

$.ajax({
   ...
   success: function(){ alert("Sucesso") }
   error: function(){ alert("Erro") }
   ...
})

I'm currently doing this:

var myFunction = function(myCallBack1, myCallBack2){
   ...
   if(...){
      myCallBack1(param);
   }else{
      myCallBack2(param);
   }
   ...
}

myFunction(
   function(param){ alert("callback 1" + param) }, 
   function(param){ alert("callback 2" + param) }
)

That is, I would just like to inform the function name and what it does, just like in ajax.

I thought about defining the function by getting a json of functions, with their specific names. But I imagine you would have a nicer way to do that.

    
asked by anonymous 21.10.2016 / 17:55

1 answer

1

You can use an argument only, options , and proceed to declare the functions within the object passed by parameter.

For example:

var myFunction = function(options){
   ...
   if(...){
      options.myCallBack1(param);
   }else{
      options.myCallBack2(param);
   }
   ...
};

myFunction({
   myCallBack1: function(param){ alert("callback 1" + param) }, 
   myCallBack2: function(param){ alert("callback 2" + param) }
});

Depending on the scenario, it is convenient to set default values for each of the callbacks or properties if they are not reported in the argument options :

function MyFunction(options){
  // mescla options com os parametros default
  options = $.extend({}, this.defaults, options);
  ...
  if(...){
    options.myCallback1();
  }else{
    options.myCallback1();
  }
  ...
}

// valores default definidos caso não sejam 
// informados os parametros
MyFunction.prototype.defauts = {
  myCallback1: $.noop,
  myCallback2: $.noop
};
    
21.10.2016 / 18:06