I’m just overworking my JS code and wish to replace my eval()‘s with window[functionName]. So I just made a quick test in the JSFiddle and all works well with the following lines:
var fnName = "Page_test";
var foo = "yammy";
var Page_test = function(bar) {
return bar;
}
var Obj = window[fnName];
alert(Obj(foo));
(Link to this JSFiddle -> http://jsfiddle.net/juSHj/)
Now I try to replace the following lines of code with the evil eval() with the above concept:
old code: (works like a charm / fired after ajax success)
...
success: function(ret) {
if(returnFnAjaxForm != "") {
eval(returnFnAjaxForm+"('"+encodeURI(jQuery.trim(ret))+"')");
}
}
...
new code:
Returns: Uncaught TypeError: Property ‘dummyFn’ of object [object
Window] is not a function
...
success: function(ret) {
if(returnFnAjaxForm != "") {
fnObj = window[returnFnAjaxForm];
if(typeof(fnObj) == "function") { // this is optional
fnObj(encodeURI(jQuery.trim(ret)));
}
}
}
...
I’m curious where I made my mistake. Yes the function I try to fire exists and is defined with var . Is this concept may not possible to use it on an ajax-response?
Thanks for any help.
(Using jQuery)
If you declare your function in a closure, it’s not a member of window. Example :
So be careful of where you declare your
Page_testvariable. If you really want to put in window, you can dowindow.Page_test = Page_test.The best you can do is to use an object for all your possible callbacks. Like this :