开发者

JS: Using variable names to call function

Im working with jQuery. I have an app that makes ajax requests to server that responds with JSON.

in some cases the response from the server will indicate the name of a JS function to be called

{"responseType":"callback", "callback":"STUFF.TestCallback","callbackData":"this is in the callback"}

If the responseType is "callback" as above the JSON is passed to a function to handle this response type. (the var "response" contains the JSON above)

STUFF.callback = function(response){
    if(typeof response.callback =='function'){
        console.log("All Good")
        response.callback(response);
    }else{
        console.log("Hmm... Cant find fun开发者_如何学Goction",response.callback );
    }
}


STUFF.TestCallBack = function(data){
    alert("it worked"); 
}

But when I do this I get the error "response.callback is not a function".

Any comments on why this is not working and how to do this properly would be greatly appreciated.


A String is a String, not a Function.

response.callback() doesn't work because it is the same as "STUFF.TestCallback"() not STUFF.TestCallback()

You probably want to have the data structured something more like "callback": "TestCallback" then then do:

STUFF[response.callback](response);

Here you use the String to access a property of STUFF. (foo.bar and foo['bar'] being equivalent.)


You could transform that "namespace.func" into a call like this:

STUFF.callback = function(response) {
  var fn = response.callback.split("."), func = window;
  while(func && fn.length) { func = func[fn.shift()]; }
  if(typeof func == 'function') {
    console.log("All Good")
    func(response);
  } else{
    console.log("Hmm... Cant find function", response.callback);
  }
}

What this does it grab the function by getting window["STUFF"] then window["STUFF"]["TestCallback"] as it loops, checking if each level is defined as it goes to prevent error. Note that this works for any level function as well, for example "STUFF.One.Two.func" will work as well.


You propably could do

var myfunction = eval(response.callback);
myfunction(response);

although using eval() is considered as a bad style by some javascript developers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜