Reputation: 3657
I am setting up a brand new site and structuring my javascript in a way that seems to make sense to me. I have created a site namespace, along with a widget/functionality 'namespace' that encapsulates methods for those widgets/functionalities. I have scoped each 'namespace' in a way that any given page on a site can call certain (public) methods to instantiate widgets/functionalities.
Here's an example of my javascript structure:
var THESITE = THESITE || (function(){
navigation = function(){
var init = function(){
// do navigation stuff
}
return {
init : init
}
},
widgets = {
widget1 : (function(){
var newWidget = function(){
// do widget1 stuff
}
return {
newWidget : newWidget
}
})(),
widget2 : (function(){
var newWidget = function(){
// do widget2 stuff
}
return {
newWidget : newWidget
}
})(),
widget3 : (function(){
var newWidget = function(){
// do widget3 stuff
}
return {
newWidget : newWidget
}
})();
},
init = function(){
navigation.init();
}
return {
init: init,
navigation: navigation,
widgets: widgets,
}
})();
THESITE.init();
And an example of how one of these methods would be called:
THESITE.widgets.widget3.newWidget();
Is this way of structuring my javascript practical/common?
Upvotes: 3
Views: 138
Reputation: 531
Yes, I would say that your structure is common. However for a larger project it would be practical to keep modules/widgets in separate files and use namespacing to ensure that collisions in the global scope does not occur. See the thread that @chris-allen suggested for more information on good ways to structure your code.
Upvotes: 1