I want to write such a function:
function doGoodJob(someId, callBackfunction){
// some stuff with someId
// todo: RUN callBackFunction here
}
They say eval is 'dangerous' in terms of code injection.
so, what is the best practice to write a JavaScript function that accepts a call-back function and runs it securely?
Is your callback a string or an actual function ?
If its a function..
function doGoodJob(someId,callbackFunction)
{
callbackFunction();
}
doGoodJob(1,function(){alert('callback');});
If its a string you can use the Function constructor.
function doGoodJob(someId,callbackFunction)
{
var func = new Function(callbackFunction)
func();
}
doGoodJob(1,"alert('test');");
Or test for both..
function doGoodJob(someId,callbackFunction)
{
var func = (typeof callbackFunction == 'function') ?
callbackFunction : new Function(callbackFunction);
func();
}
doGoodJob(1,function(){alert('callback');});
doGoodJob(1,"alert('test');");