1

I have an ExtJs application which loads quite a good number of javascript files. This leads to alot of overhead and hence we are now loading the javascript files using Ajax.

Thus, when user clicks a button, then the javascript file carrying the function associated with the button is loaded using Ajax following way:

Ext.Ajax.request({
    url:'filePath',
    success:function(response){
        eval(response.responseText);
        functionAssociatedWithButton();//Calling here the function associated with button
    },
    failure:function(){
        return;
    }
});

functionAssociatedWithButton();//Calling here the same function throws an error of function being undefined

The issue is that this function - functionAssociatedWithButton() - which is present in the JS file loaded using Ajax, is available and gets executed only in the success function of Ajax request.

But if we try accessing this function in any other section of the script then JS engine throws an error - functionAssociatedWithButton() is not defined.

How could such a function, which is present in the JS file loaded using Ajax, be made available in the rest of the script?

I tried using the 4th option suggested here - but this too didn't resolve the issue.

Could anyone please throw some light on this.

Thanks in advance.

PS: The complete script is written inside onReady function of ExtJS. Also, considering the possibility that Ajax might not have loaded by the time function is called somewhere else, I have tried this case by calling the function after Ajax has finished loading (using isLoading() and setTimeOut()) but even when the Ajax has finished loading, the function gets to be recognized only in the success function of Ajax and not recognized anywhere else in the script.

netemp
  • 4,115
  • 12
  • 43
  • 63

1 Answers1

1

This to do with the scope of the function which you have created. The function will only be available within the success function; you effectively end up with the following scenario:

function foo() {
    function bar() {
        window.alert("hello");
    }
}

console.log(typeof foo); // function
console.log(typeof bar); // undefined

You could have a global namespace object which you add the function to, something like:

var test = {};

function foo() {
    test.bar = function () {
        window.alert("hello");
    }
}

console.log(typeof foo); // function
foo();
console.log(typeof test.bar); // function
jabclab
  • 14,786
  • 5
  • 54
  • 51
  • Thanks Jack for suggesting about the global namespace. Your suggestion and this discussion here - http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string - did the trick. Cheers. – netemp Dec 05 '11 at 12:09