NOTE: I have now created a jQuery plugin which is my attempt of a solution to this issue. I am sure that it could be improved and i\'ve probably overlooked lots of use c
I think the must intuitive solution to this problem is, simply, to reduce the amount of work performed at load time.
If your code looks something like:
$(function () {
// Binds a single click event (which will never be triggered if the hypothetical
// widget is never used), regardless of how many widgets are used on the page.
$(document).delegate('.rating-widget', 'click', namespace.rating.handler);
// and so on for similar things which simply require event handler registration
// Initializes each of the forms on the page, letting the initializer take care
// of any details (datepicker widgets, validation, etc) based on the root element
$('form.fancy').each(namespace.fancyform.initializer);
// and so on for similar things that require initialization
// ... (for each type of thing on the page requiring initial setup,
// find the most general/high level pattern that sufficient)
});
things should be relatively maintainable, even if there are a few dozen lines. There's no complicated/interesting logic at this level to update/remember when working with the component code and, because everything at this level is trivial, it's easy to read. At this point, there's no need to invent some complicated registration system; it's not going to be any simpler than .delegate
and .each
.
Note as well that all of the above gracefully handles the case where the component is not used. In those cases, little or no work is done and no conditional logic is necessary.
For interesting ideas about how you might implement the handlers/initializers, you might want to take a look at, for example, the "Contextual jQuery in practice" talk Doug Neiner gave at jQuery Boston last week.