5

应用程序布局

我有一个应用程序,带有一个包含许多项目的侧边栏和一个显示这些项目的主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 *|               |
                  +---------+---------------+

在启动时,我初始化SidebarViewMainRouter。将SidebarView其方法附加renderItemCollection#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 中找到任何方法)获取当前路由并在渲染时突出显示该项目?

或者我的初始化只是愚蠢的,我应该以不同的方式处理事情吗?

4

1 回答 1

5

你可以做两件事:

  1. highlight_item可以跟踪应该突出显示的项目。
  2. 更新您的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集合被调用,并且一切都应该解决。

于 2012-02-10T19:54:42.653 回答