这里其实和我们熟悉的路由大同小异,也是利用hash 来操作。
看下面这个例子
var AppRouter = Backbone.Router.extend({
routes : {
'' : 'main',
'topic' : 'renderList',
'topic/:id' : 'renderDetail',
'*error' : 'renderError'
},
main : function() {
console.log('应用入口方法');
},
renderList : function() {
console.log('渲染列表方法');
},
renderDetail : function(id) {
console.log('渲染详情方法, id为: ' + id);
},
renderError : function(error) {
console.log('URL错误, 错误信息: ' + error);
}
});
var router = new AppRouter();
Backbone.history.start();
将例子中的代码复制到你的页面中。假设你的页面地址为http://localhost/index.html,请依次访问下面的地址,并注意控制台的输出结果:
http://localhost/index.html // 输出:应用入口方法
http://localhost/index.html#topic // 输出:渲染列表方法
http://localhost/index.html#topic/1023 // 输出:渲染详情方法, id为:1023
http://localhost/index.html#about // 输出:URL错误, 错误信息: about
如果上面没问题 route 就没有什么问题了,接下来就是几个function 需要了解一下:
- route()方法
在设定好路由规则之后,如果需要动态调整,可以调用Router.route()方法来动态添加路由规则及Action方法,例如:
router.route('topic/:pageno/:pagesize', 'page', function(pageno, pagesize){
// todo
});
// 或者 正则
router.route(/^topic/(.*?)/(.*?)$/, 'page', function(pageno, pagesize){
// todo
});
- navigate()方法
上面的例子都是通过页面点击触发router到对应的方法上,在实际的使用中,还存在一种场景就是需要在某一个逻辑中触发某一个事件,就像是jQuery中得trigger一样
router.navigate('topic/1000', {
trigger: true
});
- stop()方法
还记得我们是通过Backbone.history.start()方法来启动路由监听的,你也可以随时调用Backbone.history.stop()方法来停止监听,例如:
router.route('topic/:pageno/:pagesize', 'page', function(pageno, pagesize) {
Backbone.history.stop();
});
运行这段代码,并访问URL:http://localhost/index.html#topic/5/20,你会发现这个Action被执行之后,监听已经不再生效了。