Question

I want to finally get rid of my unstructured way of writing JS and red a lot about the "Revealing Module Pattern" lately. At least to me it seems pretty usefull, but I haven't found answers to some of my questions yet. So let's say we have some different modules in our JS, in this case "site" and "nav". The "nav" module has some private functions in it and probably some public ones as well later on. What's the best way of calling the init function in those modules. I thought of creating a public function for them and then calling them with MODULE.init();. But to me this seems like bad practice and I haven't seen it anywhere before.

$(function () {
    var site = (function () {
        var 
            module = {},
            privateVar = 3; // private variable

        function privateFunction() { // private function
            // some code here
        }

        module.init = function () {
           // global init function
        };        

        return module;
    }());

    var nav = (function () {
        var 
            module = {},
            navOpen = false; // private variable

        function open() { // private function
            // some code here
        }
        function close() { // private function
            // some code here
        }

        module.init = function () {                    
            // event handlers for open and close functions etc.
        };        

        return module;
    }());

    nav.init();
    site.init();

});

Another question, which I didn't find in any of the articles I red was how to define a global variable (like body), which I probably need in any of my modules (adding some classes to it or something). So let's say I need access to my body (like so in jQuery $("body")) in both the "nav" and "site" module. Is it better to do it like that:

$(function () {
    var site = (function () {
        var 
            module = {},
            body = $("body"); // creating the "body" variable in every module

        // .. module code
        return module;
    }());

    var nav = (function () {
        var 
            module = {},
            body = $("body"); // and again in this module

        // module code       
        return module;
    }());

});

or to have it at the very top of your JS file

$(function () {
    var
        body = $("body");

    var site = (function () {
        // module code
    }());

    var nav = (function () {
        // module code
    }());

Or is there any better way to do it / to improve my code in general? Thanks in advance for your help.

Was it helpful?

Solution

You'll get access of body variables thanks to Closure, the example here.

So, you don't need to declare some body variable inside your functions.

For the constructor issue, you already have one, is the function that you use to declare your object, see this example for detailed example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top