Skip to content

Instantly share code, notes, and snippets.

@nanto
Created July 4, 2012 16:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanto/3048295 to your computer and use it in GitHub Desktop.
Save nanto/3048295 to your computer and use it in GitHub Desktop.
Router: a router that can be combined with jquery.pjax.js
// Router: a router that can be combined with jquery.pjax.js [1]
//
// [1] https://github.com/defunkt/jquery-pjax
//
// This file is in the public domain.
//
//
// var router = new Router();
// $(document).on('pjax:end', function () { router.dispatch(location); });
// $(function () { router.dispatch(location); });
//
// router.connect(/^\/$/, function () { ... });
// router.connect(/^\/entry\/(\d+)$/, function (match, location, guard) {
// var form = $('form.comment');
// form.on('submit.myapp', function (event) { ... });
//
// // guard is a deferred's promise that may be resolved
// // when a new route is dispatched.
// guard.done(function () {
// form.off('.myapp');
// });
// });
var Router = function () {
this.routes = [];
this.guard = $.Deferred();
};
$.extend(Router.prototype, {
connect: function (path, action) {
this.routes.push([path, action]);
},
dispatch: function (location) {
this.guard.resolve(location);
this.guard = $.Deferred();
var path = location.pathname;
for (var i = 0, route; route = this.routes[i]; i++) {
var match = path.match(route[0]);
if (!match) continue;
route[1].call(this, match, location, this.guard.promise());
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment