This may have already been asked lots of times, and I've searched around SO but so far all the answers I read aren't exactly what I'm looking for.
I'm working on a website with moderate DOM elements showing/hiding, some AJAX calls, and probably something else. So I'll be having two main script files (HTML5 Boilerplate standard)
plugins.js // third party plugins here
site.js // all my site specific code here
Previously I'm using object literal design pattern, so my site.js
is something like this:
var site = {
version: '0.1',
init: function() {
site.registerEvents();
},
registerEvents: function() {
$('.back-to-top').on('click', site.scrollToTop);
},
scrollToTop: function() {
$('body').animate({scrollTop: 0}, 400);
}
};
$(function() {
site.init();
});
So far so good, it's nicely readable, all methods are public (I kinda like this, as I can test them via Chrome Dev Tools directly if necessary). However, I intend to decouple some of the site's functionality into more modular style, so I want to have something like this below the code above (or in separate files):
site.auth = {
init: function() {
site.auth.doms.loginButton.on('click', site.auth.events.onLoginButtonClicked);
},
doms: {
loginButton: $('.login'),
registerButton: $('.register')
},
events: {
onLoginButtonClicked: function() {
}
},
fbLogin: function() {
}
};
site.dashboard = {
};
site.quiz = {
};
// more modules
As you can see, it is very readable. However there is one obvious downside, which is I have to write code like site.auth.doms.loginButton
and site.auth.events.onLoginButtonClicked
. Suddenly it becomes hard to read, and it will only grow longer the more complex the functionality gets. Then I tried the modular pattern:
var site = (function() {
function init() {
$('.back-to-top').on('click', scrollToTop);
site.auth.init();
}
function scrollToTop() {
$('body').animate({scrollTop: 0}, 400);
}
return {
init: init
}
})();
site.auth = (function() {
var doms = {
loginButton: $('.login'),
registerButton: $('.register')
};
function init() {
doms.loginButton.on('click', onLoginButtonClicked);
}
function onLoginButtonClicked() {
}
return {
init: init
}
})();
// more modules
As you can see, those long names are gone, but then I guess I have to init all other modules in the site.init() function to construct them all? Then I have to remember to return the functions that need to be accessible by other modules. Both of them are okay I guess albeit a bit of a hassle, but overall, am I onto a better workflow working with modular pattern?