5

アプリケーションレイアウト

多くのアイテムを保持するサイドバーと、これらのアイテムを表示するメインdivを備えたアプリケーションがあります。シンプルなBackbone.Router、aItemsCollectionItemモデルもあります。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アタッチします。また、イベントをに添付してから、をフェッチします。renderItemCollection#allItemCollection#refreshBackbone.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")

アプリの読み込み時にアイテムを選択すると、完全に機能します。ただし、ページがURLとして読み込まれると#/show/123、アイテムは強調表示されません。highlight_itemデバッガーを実行したところ、コールバックが呼び出されたときにサイドバーがまだレンダリングされていないことがわかりました。

可能な解決策

Item#refreshイベントが最初に呼び出されSidebarView#renderてからルーティングを開始するように、バインディングを並べ替える方法はありますか?

たぶん、window.router(バックボーンドキュメントでメソッドが見つかりませんでした)から現在のルートを取得し、レンダリング時にアイテムを強調表示する回避策はありますか?

それとも、私の初期化はばかげているだけで、別の方法で処理する必要がありますか?

4

1 に答える 1

5

あなたは2つのことをすることができます:

  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 に答える