应用程序布局
我有一个应用程序,带有一个包含许多项目的侧边栏和一个显示这些项目的主div。还有一个简单Backbone.Router
的,一个ItemsCollection
和一个Item
模型。我有一个SidebarView
侧边栏和一个ShowView
来显示所选项目。
+-------------------------+
| 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 *| |
+---------+---------------+
在启动时,我初始化SidebarView
和MainRouter
。将SidebarView
其方法附加render
到ItemCollection#all
事件。我还将ItemCollection#refresh
事件附加到Backbone.history.start()
,然后获取ItemCollection
.
$(function() {
window.router = new App.MainRouter;
window.sidebar = new App.SidebarView;
ItemCollection.bind("reset", _.once(function(){Backbone.history.start()}));
ItemCollection.fetch();
});
问题
我想突出显示当前选定的项目。这通过绑定route.show
来自路由器的事件来工作:
# 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")
当我在加载应用程序时选择一个项目时,它可以完美运行。#/show/123
但是当页面作为 URL加载时,该项目不会突出显示。highlight_item
我运行调试器并发现,当调用回调时,侧边栏尚未呈现。
可能的解决方案
有没有办法重新排序绑定,以便Item#refresh
事件首先调用SidebarView#render
然后开始路由?
也许一种解决方法只是从window.router
(我没有在 Backbone Docs 中找到任何方法)获取当前路由并在渲染时突出显示该项目?
或者我的初始化只是愚蠢的,我应该以不同的方式处理事情吗?