I have a number of DHTMLX pages that I need to create and want to start structuring my JavaScript better so that I'm not polluting the global namespace.
Take the following pseudocode:
$(function() {
mainLayout = new dhtmlXLayoutObject(document.body, "2U");
mainTabBar = mainLayout.cells("b").attachTabbar();
myPage.initTab(1);
});
window.myPage = {
initTab: function(id) {
mainTabBar.addTab(id, 'TabLabel', "160px");
if (id === 1) myPage.loadViewA(id);
if (id === 2) myPage.loadViewB(id);
if (id === 3) etc etc etc....
},
loadViewA: function(id){
var innerLayout = mainTabBar.tabs(id).attachLayout("1C");
var myGrid = innerLayout.cells("a").attachGrid();
//many lines of code for creating this view, its grid, and loading data into it
var doSearch = function() {
myGrid.clearAndLoad([theUrl], "json");
};
},
//this continues on with many many other views similar to loadViewA...
}
I've tried a number of things but I can't seem to wrap my head around how to fix the code in the jQuery ready area. mainLayout
and mainTabBar
are in the global namespace because I need them down in the other myPage
functions. Ideally I would like everything in myPage
. Then I could remove the jQuery ready function from all my .js files and just put a generic one in my single HTML page like this:
$(function() {
myPage.init_or_something?();
});
Then every DHTMLX page I create would contain only with:
window.myPage = {
....
}
How do I get
mainLayout
andmainTabBar
out of the global namespace but the other function still have access to them?The
doSearch()
function needs to also be called from outside ofloadViewA()
, so it needs to be public. I think the proper way to describe the way I have it setup now is to call it a singleton. I want to do proper encapsulation so I do not want to movedoSearch()
out ofloadViewA()
because it is specifically for it. But setup this way I cannot do something like:myPage.loadViewA.doSearch()
. To do that I would have to set it up the "class" way and instantiate an object using the loadViewA constructor function, like:if (id === 1) x = new myPage.loadViewA(id);
Doing it this way and giving
loadViewA
public and private properties and method I totally understand. But I didn't go this route because there will never be more than one of these views, that's why I went with a singleton. Do I have to set it up the "class" way in order for me to properly encapsulatedoSearch()
and also have it callable from outside ofloadViewA()
?