How to pass parameters in eval in an object form?
Depends on where the function to call is defined (global scope or a local scope).
If global, you don't need eval
(and it's safer to avoid it), you just reference the function through the global window
object:
var args = [];
for(var p in json.callback.callbackParams) {
args.push(json.callback.callbackParams[p]);
}
window[json.callback.callbackName].apply(null, args)
See the apply()
function used above.
If it's in a local scope, then you need the eval
(how you have it is fine).
Don't use eval. You can get a reference to a named global variable or function from the window
object:
var callbackfunction= window[json.callback.callbackName];
And trying to serialise your values to a string just to have them parsed back to JavaScript unreliably is silly. Call the function explicitly:
callbackfunction.call(window, json.callback.callbackParams.param1, json.callback.callbackParams.param2);
(window
here is a dummy value for this
for when you're not using object methods.)
Better for automating it to accept any number of parameters would be to turn callbackParams into a plain Array:
callbackParams: [1, 2]
and then use apply
to call the function:
callbackfunction.apply(window, json.callback.callbackParams);