编辑:这个问题与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