0

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 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks David! Makes perfect sense in hind sight!
1

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.

Comments

0

You propably could do

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

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

1 Comment

Bad style. Hard to maintain. Hard to debug. Slow and inefficient. Good source of security problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.