In my job I write a lot of small JS/jQuery "snippets" for changing the default behaviour in the base product according to what the customer wants.
I tend to organize it so that I have one .js
file per view (we use ASP.NET MVC) and in this view-specific file I put all modifications relevant to that view. This is often code that is very tight-coupled to the HTML of the view. I tend to group similar "actions" into their own anonymous functions which are self-executable and then write a comment about what this portion of code does so that I don't have this huge blob of a file which I cannot navigate.
Sample:
(function ($, viewData, undefined) {
// Setup some config and some function and do something on DOM ready.
var someConfig = {
something: viewData.something,
somethingElse: viewData.somethingElse
};
function someFunction() {
return someConfig.something && someConfig.somethingElse;
}
$(function () {
if (someFunction())
$('#something').css('background-color', 'red');
});
})(jQuery, viewData);
(function ($, undefined) {
// Hide stuff on click maybe, no preparation.
$(function () {
$('body').delegate('.hide', 'click', function () {
var that = $(this);
that.hide();
});
});
})(jQuery);
http://jsfiddle.net/vikekh/9Rfs6/
If something is reusable I break it out into a global plugin/module, accessible via window.myModule
or extend jQuery with my own selectors or chaining functions.
Feel very free to comment on my approach, pros and cons and so on. I'm not very keen on pushing for module frameworks such as RequireJS as other JS developers here may not be interested in using these frameworks. Also, feel free to comment about any other errors in my code -- JS is difficult to write correctly in my opinion.