一直在学习Javascript和修改一个很酷的autocomplete library ,我现在在这个面前:
我需要检查在对象字面量中传递的东西是否是变量/字段(即被视为简单值)或者是可以调用的东西。
(因为我的自动完成依赖于许多输入字段,我需要在 Ajax.Request 之前“评估”正确的东西)以便这个声明(见“额外”部分......)
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; }
}
请参阅下面的“1//这里我迷路了...”,而不是 1 => 我想检查 extraParametersForAjaxRequest[x] 是否可调用,如果是则调用它,仅保留如果不是,它的值(value)。因此,我得到了我的其他输入的正确值(value)......同时保持了一个真正通用的方法和对该库的干净修改......
{
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 );
最佳答案
你可以做一个typeof看参数是不是一个函数,如果是就调用它。
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;
}
}
关于Javascript,在对象文字中传递一个函数,它是可调用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837275/