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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With