views:

253

answers:

3

I have a JSON object with a key element called callback.

{
"id":34,
"description":"",
"item_id":4,
"callback":"addNew",
"filename":"0000072.doc",
"type":"News",
"ext":"doc",
"size":46592
}

I would like to call the javascript "addNew" function. I tried.

json.callback(json);

But does not work. Any idea?

A: 

Use eval(json.callback+'()');

Thinker
eval is slow and dangerous
David Dorward
and unnecessary...
annakata
Come on! Two minus votes. The guy tried to help! i vote you one up!
Sergio del Amo
He may have tried, but he advised poorly. This is not just a poor answer, it's downright dangerous and should be downvoted accordingly.
Garry Shutler
Thanks Sergio for your comment. Sorry if my solution wasn't good.
Thinker
@Garry +1 - The tooltips for the votes use the term "helpful" not "effort".
David Dorward
Me and @Thinker did not know about the danger of eval. So his answer and both @David Dorward's and @Fabien Ménager's answers helped us to learn about it. So, Thinker's answer brought some value. It is clear which answers are more correct (+11 or +9 vs -1), so I do not see any need to punish him with minus votes.I think punishing so hard only discourage users to provide answers.
Sergio del Amo
+11  A: 

Assuming it is a global function (it shouldn't be):

window[json.callback](json);

If your code is well structured you will probably have an object containing all the functions the JSON could call.

var myObject = {
  func1: function myObject_func1_method(foo) {
    return 1;
  },
  func2: function myObject_func2_method(foo) {
    return 2;
  }
}

Then you can:

myObject[json.callback](json);
David Dorward
+9  A: 

Don't use eval, use

window[json.callback](json);

If the function is in the global scope. Use the scope instead of window otherwise.

Fabien Ménager