I am building a three-way selector: companies, departments and users.
I am trying to figure out the best way to structure this in my Backbone app. Here's the current problem I'm having.
Say a user has selected a company. Then, the departments and user collections will be populated and the view will update:
The user can then select a department from the list, which will further refine the user select. This I have working well.
Or, the user can go straight to User list and find a user (without first having to specify a department). In this case, the view for both departments and users needs to update:
- The department should become selected on the user's department.
- The users should refine to all users in the selected user's department, rather than all user's in the selected company.
I am struggling with the best way to do this. So far, my departments
and users
collections have a selected
property, so that's how I'm maintaining state. Currently I'm doing something like
- When the user selects a department, the department view
- Sets the selected department directly on the
departments
collection - Triggers an event
- The users collection hears the event, clears out any selected user, and triggers another event
- The users view hears the event, and re-renders. Since it knows about the departments collection, it knows a department has been selected and that it should refine the users down to the department
- Sets the selected department directly on the
I do this because if I had the view only trigger the event (without setting the departments selected property first), I would have a race condition: both the departments and users collections would be responding to the event, and depending on the timing the users may not be properly refined.
The second piece:
- When the user selects a User (without specifying a department), the user view
- Sets the selected user directly on the
users
collection - Sets the selected department directly on the
departments
collection (which it knows about) - Triggers an event
- Sets the selected user directly on the
and this is where I'm stuck. The departments collection doesn't really need to do anything, since its selected property is already correct; really, its view just needs to re-render. And so does the users' view.
But this is not all, because there are lots of other things that can happen. I feel like it's getting out of control.
- What's the best to structure this?
- Am I using events properly?
- How do you deal with a view that needs to hear about other views and other collections changing?
Update: Should I just use routes to save application state? This may simplify things...
Update 2: This question has been helpful to me. Having a separate model to manage state definitely seems the way to go.
Update 3: Having a separate model to store state + the use of jQuery deferreds is amazing. Seriously. It completes me.