アプリケーションレイアウト
多くのアイテムを保持するサイドバーと、これらのアイテムを表示するメインdivを備えたアプリケーションがあります。シンプルなBackbone.Router
、aItemsCollection
と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")
アプリの読み込み時にアイテムを選択すると、完全に機能します。ただし、ページがURLとして読み込まれると#/show/123
、アイテムは強調表示されません。highlight_item
デバッガーを実行したところ、コールバックが呼び出されたときにサイドバーがまだレンダリングされていないことがわかりました。
可能な解決策
Item#refresh
イベントが最初に呼び出されSidebarView#render
てからルーティングを開始するように、バインディングを並べ替える方法はありますか?
たぶん、window.router
(バックボーンドキュメントでメソッドが見つかりませんでした)から現在のルートを取得し、レンダリング時にアイテムを強調表示する回避策はありますか?
それとも、私の初期化はばかげているだけで、別の方法で処理する必要がありますか?