canjs基础教程之Route

本文深入解析了CanJS路由的核心组件can.route,详细介绍了其工作原理、使用方法及与URL的交互,并展示了如何通过模板自定义路由,以及如何在路由变化时触发事件和更新URL。同时,阐述了如何利用can.route构造URL和创建链接,为前端路由管理提供了实用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Routing

can.route 是CanJS路由的核心功能,也是一个特殊的Observe,当window.location.hash的值有变动时,can.route的属性值也会更新;同样,can.route的属性值有变动时,window.location.hash的值也会有更新。
可以给can.route附加一个传递URL属性的模板
Eg:

1.  // Give can.route a template.
2.  can.route(':type/:id');
3.  
4.  // If you set a hash that looks like the route...
5.  window.location.hash = '#!todos/5';
6.  // ... the route data changes accordingly.
7.  can.route.attr(); // {type: 'todos', id: 5}
8.  
9.  // If the route data is changed...
10. can.route.attr({type: 'users', id: 29});
11. // ...the hash is changed using the template.
12. window.location.hash; // '#!users/7'
13. 
14. // You can also supply defaults for routes.
15. can.route('', {type: 'recipe'});
16. 
17. // Then if you change the hash...
18. window.location.hash = '';
19. // ...the route data reflects the defaults.
20. can.route.attr(); // {type: 'recipe'}

Listening to events

因为can.route也是一个Observe,所以也可以在它上面绑定监听事件

    can.route.bind('id', function(ev, newVal, oldVal) {
        console.log('The hash\'s id changed.');
    });

你也可以在Control中监听 routing events:

    var Routing = can.Control({
        'route': function() {
        // Matches every routing change, but gets passed no data.
        },
        'todos/:id route': function(data) {
            // Matches routes like #!todos/5,
        // and will get passed {id: 5} as data.
        },
    ':type/:id route': function(data) {
            // Matches routes like #!recipes/5,
        // and will get passed {id: 5, type: 'recipes'} as data.
        }
    })

can.route.url:
根据当前的route,添加route属性并构造URL

can.route(':type/:id', {type: 'todos'});
can.route.url({id: 7}); // #!todos/7

can.route.link:同can.route.url功能类似,但它是用来构造HTML中的A(链接元素)的href,同时也可为A元素添加一些属性。

var a = can.route.link('Todo 5',{id: 7},{className: 'button'});
a; // <a href="#!todos/7" class="button">Todo 5</a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值