views:

44

answers:

3

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 function",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.

+3  A: 

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.)

David Dorward
Thanks David! Makes perfect sense in hind sight!
Alex
A: 

You propably could do

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

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

thejh
Bad style. Hard to maintain. Hard to debug. Slow and inefficient. Good source of security problems.
David Dorward
+1  A: 

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.

Nick Craver