Skip to content

Instantly share code, notes, and snippets.

@nanto nanto/router.js

Created Jul 4, 2012
Embed
What would you like to do?
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
You can’t perform that action at this time.