Last active
July 21, 2018 08:11
-
-
Save apcomplete/4113645 to your computer and use it in GitHub Desktop.
Simple backbone routing without hash URLs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r(function() { | |
Backtrace = {}; | |
Backtrace.Router = (function() { | |
Router.prototype.optionalParam = /\((.*?)\)/g; | |
Router.prototype.namedParam = /:\w+/g; | |
Router.prototype.splatParam = /\*\w+/g; | |
Router.prototype.escapeRegExp = /[-{}[\]+?.,\\^$|#\s]/g; | |
Router.prototype.rootURL = ""; | |
Router.prototype.routes = { | |
}; | |
function Router() { | |
this.initialize.apply(this); | |
this.execRoute(); | |
return this; | |
} | |
Router.prototype.initialize = function() {}; | |
Router.prototype.routeToRegExp = function(route) { | |
route = route.replace(this.escapeRegExp, '\\$&').replace(this.optionalParam, '(?:$1)?').replace(this.namedParam, '([^\/]+)').replace(this.splatParam, '(.*?)'); | |
return new RegExp('^' + route + '$'); | |
}; | |
Router.prototype.execRoute = function() { | |
var path, route, _results; | |
path = window.location.pathname.substring(this.rootURL.length+1); | |
_results = []; | |
for (route in this.routes) { | |
if (this.routeToRegExp(route).test(path)) { | |
var args = this._extractParameters(this.routeToRegExp(route), path); | |
this[this.routes[route]].apply(this,args); | |
} | |
} | |
}; | |
Router.prototype._extractParameters = function(route, fragment) { | |
var params = route.exec(fragment).slice(1); | |
return _.map(params, function(param) { | |
return param ? decodeURIComponent(param) : null; | |
}); | |
}; | |
return Router; | |
})(); | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I've been looking a long time for at solution like this, thanks a lot, and it almost works:) I have an issue with the paths when they contain parameters ... eg. mysite.com/case/1232 and I refresh the page.
This is my markup:
This is my JS:
Have you got any idea why this does not work, when I add a parameter. Se an example
Thanks.