The Application Layout
I have an application, with a sidebar that holds many items and a main div which displays these items. There is also a simple Backbone.Router, a ItemsCollection and a Item model. I’ve got a SidebarView for the sidebar and a ShowView to show the selected item.
+-------------------------+
| http://app.de/#/show/3 | <-- Current URL
+-------------------------+
| Sidebar | Main |
|---------+---------------|
| Item 1 | |
SidebarView --> |---------| Display |
| Item 2 | Item 3 | <-- MainView handled by
|---------| here | MainRouter
Selected Item --> | Item 3 *| |
+---------+---------------+
On startup, I initialize the SidebarView and the MainRouter. The SidebarView attaches its render method to the ItemCollection#all event. I also attach the ItemCollection#refresh event to Backbone.history.start(), then I fetch the ItemCollection.
$(function() {
window.router = new App.MainRouter;
window.sidebar = new App.SidebarView;
ItemCollection.bind("reset", _.once(function(){Backbone.history.start()}));
ItemCollection.fetch();
});
The problem
I want to highlight the currently selected item. This works by binding the route.show event from the router:
# I removed all code which is not necessary to understand the binding
class SidebarView extends Backbone.View
el: ".sidebar"
initialize: () ->
window.router.bind 'route:show', @highlight_item
# The route is routed to #/show/:id, so I get the id here
highlight_item: (id) ->
$(".sidebar .collection .item").removeClass("selected")
$("#item-" + id).addClass("selected")
It works perfectly when I select an Item when the app is loaded. But when the page is loaded with #/show/123 as the URL, the item is not highlighted. I run the debugger and found out, that the sidebar is not rendered yet, when the highlight_item callback is invoked.
Possible solutions
Is there any way to reorder the bindings, so that the Item#refresh event invokes SidebarView#render first and then start the routing?
Maybe a workaround that just takes the current route from the window.router (I did not find any method in the Backbone Docs) and highlights the Item when its rendered?
Or is my initialization just stupid and should I handle things differently?
You could do two things:
highlight_itemcould keep track of which item is supposed to be highlighted.renderto initialize the highlighted item.Something like this:
So, as long as
highlight_itemgets called,highlight_currentwill also get called with the appropriate@highlighted_idset and everything should work out.