Search code examples
jquerydocument-readyself-executing-function

How to use jQuery.ready with other anonymous self executing functions?


The more I read about self-executing anonymous functions, the more confused I get :)

My question is: if I use jQuery's document.ready function, do I have to place my entire app logic inside that function? If I have code in some other self-executing, anonymous function, how do I trigger that code from within the document.ready call? (without putting any variables in the global namespace?)

Document.ready code:

$(document).ready(function() {
    // how do I trigger another s.e.a.f. here?  
    var myApp = new App();
    myApp.initialize();
});

My app logic in a s.e.a.f.:

(function(window){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
        }
   }
   // how do I prevent putting 'App' in the global space?
   window.App = App;
})(window);

Solution

  • You can't.

    The only way to communicate with a function outside your scope is to put an object somewhere in the global scope.

    Instead, you should call $(document).ready() inside the IIFE, so that it will be able to access local variables via closures.