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

382 views Asked by At

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

There are 2 answers

0
SLaks On BEST ANSWER

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.

1
Popnoodles On

"how do I trigger that code from within the document.ready call"

Make sure the app logic exists first and that you use the function name you wrote.

(function(window){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
            console.log('initialised');
        }
   }
   window.App = App;
})(window);

$(function(){
    var myApp = new App();
    myApp.initializeApp();  // not myApp.initialize(); 
});

but

// how do I prevent putting 'App' in the global space?

this is a separate question...

Use a separate instance.

jQuery(document).ready(function($){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
            console.log('initialised');
        }
   }
   // how do I prevent putting 'App' in the global space?

    var myApp = new App();
    myApp.initializeApp();    
});

jQuery(document).ready(function($){
    var myApp = new App(); // this will throw an error - it doesn't exist here
});