What is the best practice for optional success and error callbacks in a function like this? Does this method make sense? It seems a little bloated to me.
Function Declaration:
var myFunc = function(myNumber, options){
options = options || {};
options.onSuccess = options.onSuccess || function(){};
options.onError = options.onSuccess || function(){};
var myNewNumber = myNumber * 2;
if(newVar > 10){
options.onSuccess(myNewNumber);
}else{
options.onError(myNewNumber);
}
}
Calling it with callbacks:
myFunc(2,{
onError: function(myNewNumber){
// do stuff
},
onSuccess: function(myNewNumber){
// do stuff
}
})
Calling it without callbacks:
myFunc(2);
I would do it by checking the existence of the functions before calling them:
It depends how many times you are likely to call these callbacks. If it is all over the place then your way might be better, or at least cleaner code.