How can I achieve this using javascript?
var x = 'function(){ ... }'
x = x.toFunction();
x();
Previously, I used var x = '...'; eval(x)
, but I have learned that this method is inefficient and slow.
To provide some context, my goal is to execute a function passed as an attribute to <loaded>
. For instance:
HTML
<p loaded="test, function(){alert('it worked!')}">
AngularJS
.directive('loaded', function() {
return {
restrict: 'A',
link: function(scope, elem, attr) {
var paramOne = attr.loaded.substr(0, attr.loaded.indexOf(',')) //paramOne = test
var paramTwo = attr.loaded.substr(paramOne.length+1).trim() //paramTwo = "function(){alert('it worked!')"
if (paramOne==='test') paramTwo() //Previously, eval(paramTwo) was used here
}
}
})
Check out the jsfiddle for more information.
*EDIT: * I am hesitant to post this as the final answer as I'm still uncertain. There might be a better approach.
var x = "function(){alert('it worked!')";
x = new Function('(' + x + ')()');
x(); //this triggers an alert saying 'it worked!'
Please advise if my edit is a valid solution or if there is a different way to go about it