Created
July 4, 2012 16:51
-
-
Save nanto/3048295 to your computer and use it in GitHub Desktop.
Router: a router that can be combined with jquery.pjax.js
This file contains hidden or 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
// 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