Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var routes = (function(history){
- // configura função pushState para checar rotas
- var pushState = history.pushState;
- history.pushState = function(state) {
- typeof(history.onpushstate) == "function" && history.onpushstate({state: state});
- setTimeout(routes.check, 10);
- return pushState.apply(history, arguments);
- };
- // classe
- var routes = {
- root: '/',
- routes: [],
- // função para executar sempre que checar as rotas
- alwaysFunc:function(){},
- // função para atualizar configurações
- config: function(options) {
- for(option in options)
- this[option] = options[option];
- return this;
- },
- // configura uma rota
- on: function(re, handler) {
- this.routes.push({ re: re, handler: handler});
- return this;
- },
- // configura rota padrão
- default: function(handler) {
- this.routes.push({ re: '', handler: handler});
- return this;
- },
- // faz a checagem das rotas
- check: function(f) {
- // pega raiz da url
- var root = routes.clean(routes.root);
- // pega caminho da url
- var path = decodeURI(location.pathname);
- path = routes.clean(path);
- path = routes.clean(path.replace(new RegExp("^"+root), ''));
- // checa qual a função configurada da rota
- for(var i=0; i<routes.routes.length; i++) {
- var match = path.match(routes.routes[i].re);
- if(match) {
- match.shift();
- routes.routes[i].handler.apply({}, [match]);
- break;
- }
- }
- // chama alguma função pré-configurada
- routes.alwaysFunc(path);
- // returna classe
- return routes;
- },
- // limpa barras da url
- clean: function(path) {
- return path.replace(/\/$/, '').replace(/^\//, '');
- },
- // configura função que sempre execura na checagem das rotas
- always: function(func){ this.alwaysFunc = func; }
- };
- // adiciona filtro de evento toda vez que a url muda pelo navegador
- window.addEventListener('popstate', routes.check);
- // inicia classe quando o documento estiver carregado
- window.addEventListener('DOMContentLoaded', routes.check);
- // returna classe
- return routes;
- })(window.history);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement