routie-0.3.0.min.js 2.5 KB

12345678
  1. /*!
  2. * routie - a tiny hash router
  3. * v0.3.0
  4. * https://github.com/jgallen23/routie
  5. * copyright JGA 2012
  6. * MIT License
  7. */
  8. (function(e){var t=[],n={},r=function(e,t){this.name=t,this.path=e,this.keys=[],this.fns=[],this.params={},this.regex=i(this.path,this.keys,!1,!1)};r.prototype.addHandler=function(e){this.fns.push(e);var t=u();a(t,this)},r.prototype.removeHandler=function(e){for(var t=0,n=this.fns.length;t<n;t++){var r=this.fns[t];if(e==r){this.fns.splice(t,1);return}}},r.prototype.run=function(e){for(var t=0,n=this.fns.length;t<n;t++)this.fns[t].apply(this,e)},r.prototype.match=function(e,t){var n=this.regex.exec(e);if(!n)return!1;for(var r=1,i=n.length;r<i;++r){var s=this.keys[r-1],o="string"==typeof n[r]?decodeURIComponent(n[r]):n[r];s&&(this.params[s.name]=o),t.push(o)}return!0},r.prototype.toURL=function(e){var t=this.path;for(var n in e)t=t.replace("/:"+n,"/"+e[n]);t=t.replace(/\/:.*\?/g,"/").replace(/\?/g,"");if(t.indexOf(":")!=-1)throw new Error("missing parameters for url: "+t);return t};var i=function(e,t,n,r){return e instanceof RegExp?e:(e instanceof Array&&(e="("+e.join("|")+")"),e=e.concat(r?"":"/?").replace(/\/\(/g,"(?:/").replace(/\+/g,"__plus__").replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,function(e,n,r,i,s,o){return t.push({name:i,optional:!!o}),n=n||"",""+(o?"":n)+"(?:"+(o?n:"")+(r||"")+(s||r&&"([^/.]+?)"||"([^/]+?)")+")"+(o||"")}).replace(/([\/.])/g,"\\$1").replace(/__plus__/g,"(.+)").replace(/\*/g,"(.*)"),new RegExp("^"+e+"$",n?"":"i"))},s=function(e,i){var s=e.split(" "),o=s.length==2?s[0]:null;e=s.length==2?s[1]:s[0],n[e]||(n[e]=new r(e,o),t.push(n[e])),n[e].addHandler(i)},o=function(e,t){if(typeof t=="function")s(e,t);else if(typeof e=="object")for(var n in e)s(n,e[n]);else typeof t=="undefined"&&o.navigate(e)};o.lookup=function(e,n){for(var r=0,i=t.length;r<i;r++){var s=t[r];if(s.name==e)return s.toURL(n)}},o.remove=function(e,t){var r=n[e];if(!r)return;r.removeHandler(t)},o.removeAll=function(){n={},t=[]},o.navigate=function(e,t){t=t||{};var n=t.silent||!1;n&&c(),setTimeout(function(){window.location.hash=e,n&&setTimeout(function(){l()},1)},1)};var u=function(){return window.location.hash.substring(1)},a=function(e,t){var n=[];return t.match(e,n)?(t.run(n),!0):!1},f=o.reload=function(){var e=u();for(var n=0,r=t.length;n<r;n++){var i=t[n];if(a(e,i))return}},l=function(){e.addEventListener?e.addEventListener("hashchange",f):e.attachEvent("onhashchange",f)},c=function(){e.removeEventListener?e.removeEventListener("hashchange",f):e.detachEvent("onhashchange",f)};l(),e.routie=o})(window);