Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a modular js design pattern? And how do I reuse a value across different modules in this model?

I've come across a javascript/jQuery design structure where each action was defined in an object literal, like this :

    if(typeof window.MYWEB === "undefined"){
        window.MYWEB = {};
    }

    MYWEB.Utils = {        
        doSthgUsingWinSize: function(){
            var width = $(window).width();
            //do something using this value
        },
        doSthgElseUsingWinSize: function(){
            var width = $(window).width();
            //do something else using this value
        }
    };

    //init:
    $(document).ready(function(){
        window.MYWEB.Utils.doSthgUsingWinSize();
        window.MYWEB.Utils.doSthgElseUsingWinSize();
    });

First question: Is this a form of 'module design pattern'? (Wherever I've looked to learn about the module pattern examples, there are anonymous functions and IIFEs, and I'm getting confused as to what makes a module pattern).

Second question: In the example above, I have var width = $(window).width() twice. In this 'pattern' I'm working with, how can I abstract $(window).width() as a separate function object, and pass the returned result into a variable that can be accessed by the other 2 functions? - this clearly isn't good enough (edit: to clarify, $(window).width() still runs twice - I want to store the width value once and using the value twice):

    MYWEB.Utils = {
            _getWindowWidth: function(){
            return $(window).width();
        },
        doSthgUsingWinSize: function(){
            var width = MYWEB.Utils._getWindowWidth();
            //do something using this value
        },
        etc
    }

Feel like I'm missing something fundamental here, but I can't quite find the words to google it! Any help or helpful pointers would be appreciated.

like image 351
soba3 Avatar asked Feb 11 '23 05:02

soba3


1 Answers

Answer to your first question: That's a module pattern. As Addy Osmani said in his article Patterns for Large-Scale JavaScript Application Architecture:

[...] a module pattern encapsulates 'privacy', state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer's interface. [...]

Creating functions and data within an object, you are "protecting pieces from leaking into the global scope".

Answer to your second question: You can reach the width variable, setting it as an object property:

MYWEB.width = $(window).width();

If you want access it within the current context, you can do this:

MYWEB.Utils.width = $(window).width();
like image 159
Leonardo Manrique Avatar answered Feb 13 '23 18:02

Leonardo Manrique