Search code examples
javascriptfunctioncall

Javascript, passing a function in an object literal and is it callable?


always in the process of learning Javascript and modifying a cool autocomplete library, i am now in front of this :

i need to check if something passed in an object literal is a variable/field (that is to be considered as a simple value) or is something that can be called.

(as MY autocomplete depend on many input fields, i need to "value" the right things, just before the Ajax.Request) so that this declaration (see the 'extra' parts...)

   myAutoComplete = new Autocomplete('query', {
        serviceUrl:'autoComplete.rails',
    minChars:3,
    maxHeight:400,
    width:300,
    deferRequestBy:100,
    // callback function:
    onSelect: function(value, data){
                alert('You selected: ' + value + ', ' + data);
                       }
            // the lines below are the extra part that i add to the library
            //     an optional parameter, that will handle others arguments to pass
            //     if needed, these must be value-ed just before the Ajax Request... 
    , extraParametersForAjaxRequest : { 
                  myExtraID : function() { return document.getElementById('myExtraID').value; } 
    }

see the "1 // here i'm lost..." below, and instead of 1 => i would like to check, if extraParametersForAjaxRequest[x] is callable or not, and call it if so, keeping only its value if not. So that, i get the right value of my other inputs... while keeping a really generic approach and clean modification of this library...

{
  var ajaxOptions = {
    parameters: { query: this.currentValue , },
    onComplete: this.processResponse.bind(this),
    method: 'get'
  };
  if (this.options.hasOwnProperty('extraParametersForAjaxRequest'))
  {
      for (var x in this.options.extraParametersForAjaxRequest)
      {
          ajaxOptions.parameters[x] = 1 // here i'm lost...
      }
  }


  new Ajax.Request(this.serviceUrl, ajaxOptions );

Solution

  • You can do a typeof to see if the parameter is a function, and call it if it is.

    var value;
    for (var x in this.options.extraParametersForAjaxRequest)
    {
        value = this.options.extraParametersForAjaxRequest[x];
    
        if (typeof(value) == 'function') {
            ajaxOptions.parameters[x] = value();
        }
        else {
            ajaxOptions.parameters[x] = value;  
        }
    }