編輯:這個問題與this one非常相似,但它更「概念上」。理解backbone.js作爲一個整體
假設一個單頁的應用程序與靜態鏈接的反彈反映routes
:
<!-- Top navlist -->
<ul class="nav nav-list">
<li><a class="active" href="#/customers">Customers</a></li>
</ul>
<!-- Left navlist -->
<ul class="nav nav-list">
<li><a class="active" href="#/customers">Show customers</a></li>
<li><a href="#/customers/new">Create customer</a></li>
</ul>
我需要設置class="active"
一個(或多個)基於當前路線上的鏈接。哪種方法是正確的?
- 創建
Link
和LinkCollection
模型,只要LinkCollectionView
和LinkView
,從頭開始:這似乎矯枉過正給我。似乎沒用,因爲鏈接不依賴於服務器端(它們不是動態創建的)。 - 創建
Link
和LinkCollection
模型迭代現有鏈接。 - 忘記模型,併爲每條路線手動設置
class="active"
。像$('body').find('a[href="#/customers"]').addClass('active')
。似乎代碼重複給我。 - 創建一個「全局」
AppView
視圖並執行像pt。 3在render()
funcion。
路由定義的例子:
<script>
(function($){
var MyApp = { Models : {}, Collections : {}, Views : {} };
// The Router
MyApp.Router = Backbone.Router.extend({
routes : {
'/customers' : 'showCustomersView',
'/customers/new' : 'showCreateCustomerView'
},
showCustomersView : function() {
// Make customers links active
},
showCreateCustomerView : function() {
// Make new customer links active
},
});
})(jQuery);
</script>
+1的解釋。但我認爲'router.navigate'將打破MVC模式背後的哲學。這是應該檢索數據並提供正確視圖的路由器。恕我直言,這就是它應該做的。 – gremo 2012-03-05 22:09:53
可能更好地使用數據路由,這種有效的語法。 – steveax 2012-03-06 00:35:09
好的呼叫,steveax。我更新了我的答案。 Gremo,我不確定你的意思。路由器*是*檢索數據並提供視圖 - 所有這些都是讓路由器響應鏈接點擊。查詢/查看邏輯仍然在路由器中,僅此而已。 – 2012-03-06 01:42:32