Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute string as javascript function

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.

like image 579
chugh97 Avatar asked May 01 '26 23:05

chugh97


2 Answers

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);
             }
}
like image 82
Curtis Avatar answered May 04 '26 11:05

Curtis


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);