I while back I got tired of having to include bootstrapping code on all my html (aspx) pages; you know, including some sort of $(document).ready(…) to bind the correct set of handlers for the page, so I came up with a basic routing/bootstrapper to handle this in a more generic way.
The basic idea is to have an object that takes care of calling the correct method on the correct object to initialize the bindings (and anything else that needs to happen on page load) based on the URL of the page, a routing engine :).
Let’s say I’m using ASP.Net MVC, then I could organize my code so that I have one js object per controller and inside it a function for each of the actions to do the actual bootstrapping:
The controller object
Now when the user hits my “/Home/Index” URL, I need to call the appropriate methods on the controller object, and here it is:
The basic routing object
The way this works is by keeping a list of controllers and match the current URL’s controller name to the controller object and call the init() function on it, then match the action part of the URL a function inside the controller object and, if it exists, call it.
I’ve separated the part that decides the name of the controller and the action to a different object (routing strategy) so you could create a different strategy to decide the controller and action (ie. if you are not using MVC, you could use the name of the aspx page as the controller and something else for the action).
The advantage of this approach is that I could have one file for each of my js controllers neatly organized and then, during my build process combine all of them into one and minimize it.
After using this approach for a while, someone pointed out to me that this is a similar approach to Paul Irish's unobstructive DOM-ready execution which uses the body id and class attributes as the basis for selecting the what to initialize, it’s also a very good way to handle the same problem, take a look at it also.
So have fun with it!Source code on GitHub