I inherited a bunch of code that I'd like to refactor. It is a UI application written in javascript.

Current state:

We have main application which consist of several UI components. And each component has entry fields, textboxes, menus, etc), like "ticket", "customer information", etc. Based on input, where the application was called from, who is the user, we enable/disable, hide, show, change titles.

Unfortunately, the app grew to the point where it is really hard to scale, add new features. Main the driver (application code) calls set/unset functions of the respective components. So a lot of the stuff look like this

Main app unit

function1() {

call_function2() { 
       // it may repeat some of the code function1 called 

and we have a lot of this in the main union.

I am cleaning this mess. What is the best way to maintain the state of widgets? Please let me know if you need me to clarify.


I just did a similar refactor. The approach I took was instead of storing the state inside the components, store it in a semantically meaningful state variable, which is published to the components, who then manage their individual UI state accordingly.

For example, you could have a userState variable with values of unauthenticated, untrusted, trusted, or admin. Your controller functions then just have to call something like changeUserState(trusted), which in turn calls a userStateChanged(trusted) on all subscribed components, who change their UI state accordingly.

What that does for you is decentralize your UI state logic. Instead of every controller function needing to track the low-level state of every UI component, the controller functions handle high-level state, and the individual components translate the high-level state into their own low-level state.


Your issue sounds like a classic candidate for an MVC pattern.

If you continue, you'll likely end up implementing most of an MVC library, eventually. Probably your best bet is to switch to an existing one - http://javascriptmvc.com/ seems decent.

  • +1 MVC! Refactor the mess! Have program logic be separate from the UI code. Jun 24 '13 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.