Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a function accepting callBack function and run it in a 'safe' way?

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?

like image 582
pencilCake Avatar asked Apr 08 '11 11:04

pencilCake


2 Answers

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');");
like image 81
Richard Friend Avatar answered Sep 30 '22 17:09

Richard Friend


This should work:

function doGoodJob(simeOd, callBackFunction){  
    /** Do stuff **/  
    callBackFunction();  
}

quick fiddle: http://jsfiddle.net/pS67X/

like image 31
Thor Jacobsen Avatar answered Sep 30 '22 17:09

Thor Jacobsen