首页 > 语言 > JavaScript > 正文

JS实现简单路由器功能的方法

2024-05-06 16:20:55
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了JS实现简单路由器功能的方法,基于javascript模拟简单路由编码的相关技巧,需要的朋友可以参考下

本文实例讲述了JS实现简单路由器功能的方法。分享给大家供大家参考。具体实现方法如下:

 

 
  1. var wawa = {}; 
  2. wawa.Router = function(){ 
  3. function Router(){ 
  4. } 
  5. Router.prototype.setup = function(routemap, defaultFunc){ 
  6. var that = this, rule, func; 
  7. this.routemap = []; 
  8. this.defaultFunc = defaultFunc; 
  9. for (var rule in routemap) { 
  10. if (!routemap.hasOwnProperty(rule)) continue; 
  11. that.routemap.push({ 
  12. rule: new RegExp(rule, 'i'), 
  13. func: routemap[rule] 
  14. });  
  15. } 
  16. }; 
  17. Router.prototype.start = function(){ 
  18. console.log(window.location.hash); 
  19. var hash = location.hash, route, matchResult; 
  20. for (var routeIndex in this.routemap){ 
  21. route = this.routemap[routeIndex]; 
  22. matchResult = hash.match(route.rule); 
  23. if (matchResult){ 
  24. route.func.apply(window, matchResult.slice(1)); 
  25. return;  
  26. } 
  27. } 
  28. this.defaultFunc(); 
  29. }; 
  30. return Router; 
  31. }(); 
  32. var router = new wawa.Router(); 
  33. router.setup({ 
  34. '#/list/(.*)/(.*)': function(cate, id){ 
  35. console.log('list', cate, id); 
  36. }, 
  37. '#/show/(.*)': function(id){ 
  38. console.log('show', id);  
  39. } 
  40. }, function(){ 
  41. console.log('default router'); 
  42. }); 
  43. router.start(); 

希望本文所述对大家的javascript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选