techie_28 techie_28 - 6 months ago 15
Javascript Question

Evaluate jQuery code nested in the object when object is used

I have a JS object like:

{
'element1': {
'redirectURI': 'abc.php?toDate=' + encodeURIComponent(jQuery('.dateField1').val())
},
'element2': {
'redirectURI': 'pqr.php?&toDate=' + encodeURIComponent(jQuery('.dateField2').val())
}
};


I need the redirectURI index to be evaluated when the object is used i.e. when
obj['element1']['redirectURI']
or
obj['element2']['redirectURI']
.

How to achieve this?

Right now
jQuery('.dateField1').val(),jQuery('.dateField2').val()
take the values available when this object is parsed,the date field are datepicker whose value can vary.

Thanks.

Answer

Simply use functions. Don't forget to call them as functions (with "()" later).

{
  'element1': {
    'redirectURI': function() { return 'abc.php?toDate=' + encodeURIComponent(jQuery('.dateField1').val());}
  },
  'element2': {
    'redirectURI': function() {return 'pqr.php?&toDate=' + encodeURIComponent(jQuery('.dateField2').val());}
  }
};