Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a function, whose name is passed in Json object?

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?

like image 829
Sergio del Amo Avatar asked Dec 01 '22 07:12

Sergio del Amo


1 Answers

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);
like image 72
Quentin Avatar answered Dec 04 '22 05:12

Quentin