Advertisement
Guest User

Untitled

a guest
Jul 24th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1.  
  2. var routes = (function(history){
  3.  
  4. // configura função pushState para checar rotas
  5. var pushState = history.pushState;
  6. history.pushState = function(state) {
  7. typeof(history.onpushstate) == "function" && history.onpushstate({state: state});
  8. setTimeout(routes.check, 10);
  9. return pushState.apply(history, arguments);
  10. };
  11.  
  12. // classe
  13. var routes = {
  14.  
  15. root: '/',
  16. routes: [],
  17.  
  18. // função para executar sempre que checar as rotas
  19. alwaysFunc:function(){},
  20.  
  21. // função para atualizar configurações
  22. config: function(options) {
  23. for(option in options)
  24. this[option] = options[option];
  25. return this;
  26. },
  27.  
  28. // configura uma rota
  29. on: function(re, handler) {
  30. this.routes.push({ re: re, handler: handler});
  31. return this;
  32. },
  33.  
  34. // configura rota padrão
  35. default: function(handler) {
  36. this.routes.push({ re: '', handler: handler});
  37. return this;
  38. },
  39.  
  40. // faz a checagem das rotas
  41. check: function(f) {
  42.  
  43. // pega raiz da url
  44. var root = routes.clean(routes.root);
  45.  
  46. // pega caminho da url
  47. var path = decodeURI(location.pathname);
  48. path = routes.clean(path);
  49. path = routes.clean(path.replace(new RegExp("^"+root), ''));
  50.  
  51. // checa qual a função configurada da rota
  52. for(var i=0; i<routes.routes.length; i++) {
  53. var match = path.match(routes.routes[i].re);
  54. if(match) {
  55. match.shift();
  56. routes.routes[i].handler.apply({}, [match]);
  57. break;
  58. }
  59. }
  60.  
  61. // chama alguma função pré-configurada
  62. routes.alwaysFunc(path);
  63.  
  64. // returna classe
  65. return routes;
  66. },
  67.  
  68. // limpa barras da url
  69. clean: function(path) {
  70. return path.replace(/\/$/, '').replace(/^\//, '');
  71. },
  72.  
  73. // configura função que sempre execura na checagem das rotas
  74. always: function(func){ this.alwaysFunc = func; }
  75. };
  76.  
  77. // adiciona filtro de evento toda vez que a url muda pelo navegador
  78. window.addEventListener('popstate', routes.check);
  79.  
  80. // inicia classe quando o documento estiver carregado
  81. window.addEventListener('DOMContentLoaded', routes.check);
  82.  
  83. // returna classe
  84. return routes;
  85.  
  86. })(window.history);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement