Backbone 的使用 (四)—— Route 篇

这里其实和我们熟悉的路由大同小异,也是利用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被执行之后,监听已经不再生效了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值