[Template] Javascript Functions

Been dealing with Javascript functions lately, I find that these are the most-frequently-used input parameters for all a typical function:
  1. data
  2. url (optional) 
  3. callback (optional)

A good JS function should readily accept these parameters. And a typical Javascript function call would be like:
somefunction( {data: value, data2: value2 }, [url], [callback()] );
We know that in PHP we can use the following method to write a "optional" second (or third) input parameter.
function somefunction( $data, $callback = FALSE); 
This way, if the second argument is not supplied, $callback will be automatically assigned to FALSE. Its a good practice to set a default value for a variable.

After Googling around, I found that Javascript is event better at handling such case. We can take in as many optional input parameters, in no specific order. But the trade-off is, we need a check for the input parameter type.

Stackoverflow has this excellent post on the template for checking input argument type.

function getData ([id, parameters, callback]) {
  var id = arguments[0], parameters, callback;

  if (arguments.length == 2) { // only two arguments supplied
    if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
      callback = arguments[1]; // if is a function, set as 'callback'
    } else {
      parameters = arguments[1]; // if not a function, set as 'parameters'
    }
  } else if (arguments.length == 3) { // three arguments supplied
    parameters = arguments[1];
    callback = arguments[2];
  }
  
  // do something here...
  // ...
  // and finally, on complete run the callback function
  callback();
}

This is... the function template which is usually used in jQuery too!


Extras

Actually callback function can be easily done in jQuery. Not the correct way though.
jQuery.some_other_jQuery_functions().each(function(){ 
  // The functions to execute after the first function finish executing.
});

If you are new to Javascript frameworks, heres a good comparison of the performance of the popular frameworks. http://blog.creonfx.com/javascript/mootools-vs-jquery-vs-prototype-vs-yui-vs-dojo-comparison-revised


References:
http://stackoverflow.com/questions/1529077/handling-optional-parameters-in-javascript

Comments

  1. Great Info. Thanks for the your effort. Appreciate it.

    ReplyDelete
  2. Great Info. Thanks for the your effort. Appreciate it.

    http://mobisoftinfotech.com/services/cross-platform-mobile-development-usa/

    ReplyDelete

Post a Comment

Popular posts from this blog

[Azure Websites PHP] Cross Domain request results in blank response page after Preflight HTTP OPTIONS

[Magento] Create Contact Form with Dynamic Recipient