I'm in the process of building a website for the company I work for and I'm trying to think of the best way to namespace and organize the site's JavaScript code.
I've written several jQuery/JavaScript plugins for the big chunks of code, but now I'd like a namespaced place to "call" said plugins and any other random JavaScript that's needed throughout the site.
I'm considering using a singleton (NAMESPACE.js
):
// http://stackoverflow.com/a/1479341/922323
var NAMESPACE = (function() {
//var privateVar = '';
function weather() {
var $weather = $('#weather');
if ($weather.length) {
// Do jQuery stuff with $weather here.
}
} // weather()
function navigation() {
var $baz = $('#baz'),
$html = $('html');
$baz
.myOtherPlugin({
cloneRemove : 'li > div',
cloneId : false
})
.anotherPlugin({
eventType : 'hoverIntent',
onStartOutside : function() {
$html.addClass('mw-outside');
},
onEndOutside : function() {
$html.removeClass('mw-outside');
}
});
} // navigation()
function footer() {
$('footer ul').myPlugin({
//openTab : true,
currentPage : true
});
} // footer()
return {
init : function() {
weather();
navigation();
footer();
// Add more here as project grows...
} // init()
};
})();
HTML would look like so (in foot of document):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="plugins.js"></script>
<script src="NAMESPACE.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
NAMESPACE.init();
});
//-->
</script>
Question(s):
- Do you see anything out of the ordianary with my (pseudo) code above?
- Am I headed in the right direction? If not, could you suggest an alternative?
- Am I over-complicating things?
- I really like how Yahoo! does:
YAHOO.namespace("myProject"); YAHOO.myProject.myModule = function () { ... }
... it seems like if I did something similar, that would allow me to easily add/remove "modules" on a "per page" basis. Would anyone recommend this approach? If so, how could I modify my example to mimic YUI's functionality (I'm going to research YUI'snamespace()
code and post back my results if I figure it out).