My object has a call back:
var MyObject = {
CallBack: "function (whichSubMenuIsClicked, subMenuObjectTag) { self.doStuff(whichSubMenuIsClicked.SubMenuItem, whichSubMenuIsClicked.HeaderColumnName, whichSubMenuIsClicked.DivIdentifier);}",
}
The callback is a string. Now I need to execute it using MyObject.CallBack(param1, param2) How can this be done using jquery or javascript. The self in this case is the original widget calling another widget. Thus the call back is on the original widget.
4 Answers 4
Just don't have the function as a string.
Have the function as a function:
var MyObject = {
CallBack: function (whichSubMenuIsClicked, subMenuObjectTag) {
self.doStuff(whichSubMenuIsClicked.SubMenuItem, whichSubMenuIsClicked.HeaderColumnName, whichSubMenuIsClicked.DivIdentifier);
}
}
Comments
Use the Function constructor, which accepts a list of parameter names followed by the function body:
var MyObject = {
CallBack: "self.doStuff(whichSubMenuIsClicked.SubMenuItem, whichSubMenuIsClicked.HeaderColumnName, whichSubMenuIsClicked.DivIdentifier)",
};
var myfunc = new Function("whichSubMenuIsClicked", "subMenuObjectTag", MyObject.CallBack);
Comments
You should write the function as a function, as @Curt demonstrated. Only if you really have no other choice than getting it as a string (e.g. from user input), you would first need to parse it to executable code which you then could call. The way to do so is eval. A problem will become the reference self, which is not a variable inside your function and would be assumed global. Yet, you can use a with statement to work around that:
var MyObject = {
CallBack: "function (whichSubMenuIsClicked, subMenuObjectTag) { self.doStuff(whichSubMenuIsClicked.SubMenuItem, whichSubMenuIsClicked.HeaderColumnName, whichSubMenuIsClicked.DivIdentifier);}",
};
var widget = {doStuff: console.log};
var fn;
with( {self: widget} ) {
fn = eval( MyObject.CallBack );
}
fn({SubMenuItem: "...", HeaderColumnName: "...", DivIdentifier: "..."});
9 Comments
Function constructor does not seem to be able to handle the self variable.eval function would execute any malicious statements sneaked in. This is pretty much the entire point behind the hubbub over the use of eval. I'm not sure what you mean by "handling the self variable".Function does not execute any line of code - only you execute the resulting function. And malicious statements could be "sneaked" into a function body as well, there's no difference.Very bad approach but You can do it by eval()
var MyObject = { CallBack: "AName = function(param1, param2) { alert(param1 + param2); }", }
eval(MyObject.CallBack+"(1,2)");
13 Comments
eval is useful. Metaprogramming, for instance!eval is terrible, but this answers the OP's question.
eval, insecure.