JQUERY functions with named callbacks

Asked

Viewed 433 times

0

I would like to create a function with Jquery so that I can pass only 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") }
   ...
})

Currently I’m doing so:

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 name of the function and what it does, just like in ajax.

I thought of defining the function by receiving a json of functions, with their specific names. But I imagine that would have a more pleasant way of doing this.

1 answer

1


You can use one argument only, options, and start 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 will be 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
};
  • Got it. So it’s the way I imagined it, rsrs. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.