canjs基础教程之Route
2015-06-10 20:32
531 查看
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. } })
Making URLs and links
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>
相关文章推荐
- canjs基础教程之Components
- Canjs基础教程之Controls
- W3School-JS-动态原型方式定义类或对象中示例的BUG
- canjs基础教程之EJS
- 如何在加载JSP页面时,同时调用servlet中的方法
- js数组操作-数组去重
- scrapy爬虫成长日记之创建工程-抽取数据-保存为json格式的数据
- js中SetInterval与setTimeout用法
- JSON解析---初识
- JS实现简单的图片轮换效果
- javascript日期格式相减,计算出天数
- 动态网页爬取例子(WebCollector+selenium+phantomjs)
- javascript splice()插入、删除或替换数组
- echarts.js使用方法
- JavaScript 自定义对象
- 我所了解的javaScript细节
- JS中需要注意的知识点
- [技巧篇]00.TrimFilter去掉jsp页面空白,提升访问速度
- JS事件
- JavaScript中清空数组的三种方式