The web app I'm working on has several fairly complex and stateful pieces of client-side UI. I'm trying to keep things sane by organizing them into composable javascript widgets. Some of the requirements are:
1) Some of the data required to initialize the widget needs to come from the server
2) Some of the data comes from the client (based on which of a list of items is selected)
3) The state of some sections of the widget needs to be remembered when it's closed and reopened
4) The state of other sections needs to be forgotten and reset to the original setting
5) The page has to fully render very quickly, so AJAX calls need to be minimized
So, my question is, how do you organize the code for this widget? What I have currently involves sending down the HTML for the widget with some data (i.e. #1) filled in on the server side (to avoid sending down the data via an extra AJAX call). I then have a bunch of jquery code that fills in the client side stuff in an ad-hoc fashion. And then more code to reset everything back to the desired state on the second invocation. Surely there's a more declarative way to accomplish this?