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.