Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Best way to declare functions to be used globally?

My javascript file is getting pretty big (3000+ lines) and I'm getting confused as to how to layout my file and delare functions so that they can called anywhere in the file.

To summarise my JS file looks a little like this at the moment:

//ALL GLOBAL VARIABLES FIRST DECLARED HERE
var var1 , var2 ,var3

$(document).ready(function(){

//JQUERY STUFF

});

//ALL FUNCTIONS THAT NEED TO BE GLOBAL DECLARED HERE
function myFunction(){
//do some stuff here
}

I am running into problems with this as some functions I call in places don't seem to be declared at the time of calling or aren't available globaly. It's all very confusing now!

Could someone suggest the best way to layout a big js/jquery file with certain JS Functions, Objects and Variables available to be referenced anywhere in the file.

UPDATE:

So to simplify it this correct (see my comments)?

window.MainModule = (function($, win, doc, undefined) {//WHAT IS BEING PASSED IN HERE?
    var foo, bar, modules; //VARIABLES ACCESSIBLE ANYWHERE

    var modules["foobar"] = (function() {//WHAT IS A MODULE? WHEN WOULD I USE A SEPERATE MODULE?
        var someFunction = function() { ... };//DECLARING MY FUNCTIONS?

        ...

        return { 
            init: someFunction,//IS THIS WHERE I USE/BIND MY FUNCTIONS TO EVENTS AND ELEMENTS?
            ... 
        };
    }());

    // hoist a variable into global scope
    window.Global = someLocal;

    return { 
        init: function() {//FUNCTION TO INIT ALL MODULES?
            for (var key in modules) {
                modules[key].init();
            }
        }
    };
}(jQuery, this, document));
like image 607
wilsonpage Avatar asked Feb 25 '11 16:02

wilsonpage


People also ask

How do you make a function available globally in JavaScript?

Open JS console, write var x = function() {console. log('x')} and then try to call window. x() . In browsers, window is global scope, therefore the function is global.

How many ways can you declare a function in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


2 Answers

The modules section isn't properly defined ... here's a slightly tidied up example.

window.MainModule = (function($, win, doc, undefined) {
    var modules = {};

    // -- Create as many modules as you need ...
    modules["alerter"] = (function(){
        var someFunction = function(){ alert('I alert first'); };

        return { 
            init: someFunction
        };
    }());

    modules["alerter2"] = (function(){
        var someFunction = function(){ alert('I alert second'); };

        return { 
            init: someFunction
        };
    }());

    return { 
        init: function(){
            for (var key in modules){
                modules[key].init();
            }
        }
    };
}(jQuery, this, document));

$(window.MainModule.init);
like image 100
Jeff Parker Avatar answered Oct 18 '22 02:10

Jeff Parker


// We always use closures don't we?
window.MainModule = (function($, win, doc, undefined) {
    var foo, bar, modules; // List of local variables. 

    var modules["foobar"] = (function() {
        var someFunction = function() { ... };

        ...

        return { 
            init: someFunction,
            ... 
        };
    }());

    // hoist a variable into global scope
    window.Global = someLocal;

    return { 
        init: function() {
            for (var key in modules) {
                modules[key].init();
            }
        }
    };
}(jQuery, this, document));

// Let's kick off the MainModule on $.ready
// I recommend you do this in your `html` with page specific data.
$(window.MainModule.init);

[[Disclaimer]]: This is a pseudo-code module with some standard code excluded for brevity.

Anything declared with var x inside your main closure is available throughout the entire function. Of course it won't be set to what you expect it to be set unless you set it.

To control loading and flow split code into what's automatically executed in your self executing closure and what needs to manually inited by your controller with page/user specific parameters.

like image 21
Raynos Avatar answered Oct 18 '22 02:10

Raynos