Avoiding eval when executing js returned from ajax call
<p>I want to make an ajax call that will return a json object. One of this JSON object's properties will be the string of a function to be executed in the client. I realise this can easily be solved by using eval, but seeing the <a href="http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea/86580#86580">many</a> <a href="http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea/86616#86616">disadvantages</a> of eval, I'd rather avoid it. My question is:</p>

<p>Can I in some way return from the server some js code and execute it without resorting to eval?</p>

<p>As per request, here's some example code:</p>

<p>Server (Node.js):</p>

<pre><code>var testFunc = function() {
    alert('h1');
};

app.get('/testPack', function(req, res) {
    var template = jade.render('h1 hi');
    res.send({
        template : template,
        entity : testFunc.toString(),
        data : { 
            id: "OMG I love this"
        }
    });
});
</code></pre>

<p>Client:</p>

<pre><code>$(document).ready(function() {
    $.ajax({
        url: '/testPack',
        success: function(data) {
            $('body').append($(data.template))
            alert(data.data.id);
            var entity = eval(data.entity);
            entity();
        }
    })
})
</code></pre>

<p>Of course, the returned function called entity wouldn't do such a silly thing, it would expose an API of the returned widget.</p>

<p>Just to clarify, I'd like to avoid having to make a separate call for the javascript itself. I'd rather bundle it with the template and data to render.</p>
