应用布局
我有一个应用程序,它有一个包含许多项目的 sidebar 和一个显示这些项目的 main 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();
});
问题
我想突出显示当前选中的项目。这通过绑定(bind)来自路由器的 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
回调时,侧边栏尚未呈现。
可能的解决方案
有什么方法可以重新排序绑定(bind),以便 Item#refresh
事件先调用 SidebarView#render
然后开始路由?
也许有一个变通方法,它只是从 window.router
获取当前路由(我在 Backbone 文档中没有找到任何方法)并在渲染时突出显示 Item?
或者我的初始化是愚蠢的,我应该以不同的方式处理事情吗?
最佳答案
你可以做两件事:
highlight_item
可以跟踪应该突出显示的项目。- 更新您的
render
以初始化突出显示的项目。
像这样:
initialize: () ->
@highlighted_id = null
window.router.bind 'route:show', @highlight_item
render: () ->
# Set everything up inside @el as usual
@highlight_current()
@
highlight_item: (id) =>
@highlighted_id = id
@highlight_current()
highlight_current: () ->
return unless(@highlighted_id)
$(@el)
.find('.selected').removeClass('selected')
.end()
.find("#item-#{@highlighted_id}").addClass('selected')
因此,只要 highlight_item
被调用,highlight_current
也会被调用并设置适当的 @highlighted_id
并且一切都会正常进行。
关于javascript - 使用 Backbone 路由器回调突出显示所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9233540/