使用骨干路由器回调突出显示所选项目

ibl*_*lue 5 javascript jquery javascript-events coffeescript backbone.js

应用程序布局

我有一个应用程序,侧边栏包含许多项目,主要 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 *|               |
                  +---------+---------------+
Run Code Online (Sandbox Code Playgroud)

在启动时,我初始化SidebarViewMainRouter.该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();
});
Run Code Online (Sandbox Code Playgroud)

问题

我想突出显示当前选中的项目.这通过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")
Run Code Online (Sandbox Code Playgroud)

当我在加载应用程序时选择项目时,它可以正常工作.但是当页面#/show/123作为URL 加载时,项目不会突出显示.我运行调试器并发现,当highlight_item调用回调时,侧边栏尚未呈现.

可能的解决方案

有没有办法重新排序绑定,以便Item#refresh事件SidebarView#render先调用,然后启动路由?

也许一个解决方法只是从当前路线window.router(我没有在Backbone Docs中找到任何方法)并在其呈现时突出显示项目?

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

mu *_*ort 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')
Run Code Online (Sandbox Code Playgroud)

因此,只要highlight_item被调用,highlight_current也将使用适当的@highlighted_id集调用,一切都应该解决.