11 lines
2.7 KiB
JavaScript
11 lines
2.7 KiB
JavaScript
var Path={'version':"0.6",'map':function(path){if(Path.routes.hasOwnProperty(path)){return Path.routes[path];}else{return new Path.core.route(path);}},'root':function(path){Path.routes.root=path;},'rescue':function(fn){Path.routes.rescue=fn;},'match':function(path,parameterize){var params={};var parse_params=function(str){var results=[],re=/\(([^}]+?)\)/g,text;while(text=re.exec(str)){results.push(text[1]);}
|
|
return results;};var route=null;var i=null;for(route in Path.routes){if(route!==null&&route!==undefined){var optional_parts=parse_params(route);var valid_routes=[];valid_routes.push(route.split("(")[0]);for(var j=0;j<optional_parts.length;j++){valid_routes.push(valid_routes[valid_routes.length-1]+optional_parts[j]);}
|
|
for(var x=0;x<valid_routes.length;x++){var rroute=valid_routes[x];var compare=path;if(rroute.search(/:/)>0){for(i=0;i<rroute.split("/").length;i++){if((i<compare.split("/").length)&&(rroute.split("/")[i][0]===":")){params[rroute.split('/')[i].replace(/:/,'')]=compare.split("/")[i];compare=compare.replace(compare.split("/")[i],rroute.split("/")[i]);}}}
|
|
if(rroute===compare){if(parameterize){Path.routes[route].params=params;}
|
|
return Path.routes[route];}}}}
|
|
return null;},'dispatch':function(){if(Path.routes.current!==location.hash){Path.routes.previous=Path.routes.current;Path.routes.current=location.hash;var match=Path.match(location.hash,true);if(match!==null){match.run();}else{if(Path.routes.rescue!==null){var previous_route=Path.match(Path.routes.previous);if(previous_route!=null&&previous_route.do_exit!==null){previous_route.do_exit();}
|
|
Path.routes.rescue();}}}},'listen':function(){if(location.hash===""){if(Path.routes.root!==null){location.hash=Path.routes.root;}}else{Path.dispatch();}
|
|
if("onhashchange"in window){window.onhashchange=Path.dispatch;}else{setInterval(Path.dispatch,50);}},'core':{'route':function(path){this.path=path;this.action=null;this.do_enter=[];this.do_exit=null;this.params={};Path.routes[path]=this;}},'routes':{'current':null,'root':null,'rescue':null,'previous':null}};Path.core.route.prototype={'to':function(fn){this.action=fn;return this;},'enter':function(fns){if(fns instanceof Array){this.do_enter=this.do_enter.concat(fns);}else{this.do_enter.push(fns);}
|
|
return this;},'exit':function(fn){this.do_exit=fn;return this;},'run':function(){var halt_execution=false;if(Path.routes.previous){var previous=Path.match(Path.routes.previous,false);if(previous&&previous.do_exit!==null){previous.do_exit();}}
|
|
if(Path.routes[this.path].hasOwnProperty("do_enter")){if(Path.routes[this.path].do_enter.length>0){for(var i=0;i<Path.routes[this.path].do_enter.length;i++){result=Path.routes[this.path].do_enter[i]();if(result===false){halt_execution=true;break;}}}}
|
|
if(!halt_execution){Path.routes[this.path].action();}}}; |