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'}
因为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>