I got following nested View structure:
LayoutView
- SidebarView
- ContactListView
- ContactItemView
- ContentView
Now imagine following situation:
A user clicks on a ContactItem. Now the ContactItem should call an event or something else which renders the profile of the clicked contact in the ContentView.
I have no idea how I could do this without breaking the flexibility…
You probably want to use Events to hook them together, rather than having the ContactItemView directly call the ContentView. As you’re creating the views, each parent view can bind to the child view’s events. Then when the click happens, it will bubble up through the chain until the appropriate view handles it.
Here’s a simple example to show the general idea. I’m presenting this in the order that the event bubbling happens, which is hopefully a little bit clearer.
First, the ContactItemView gets the DOM click event and triggers a Backbone event for it.
The ContactListView can listen for that and republish it:
The SidebarView listens for that event, and actually knows what to do with it:
This way your ContactItemView doesn’t know anything about the parent views, so it can be more flexible. The downside is it’s a lot of boilerplate code. Maybe someone else will have a cleaner approach, but this does the trick for me.