page.js
page.js copied to clipboard
Is it possible to intercept change of url requests
There are two common use cases for this:
- Some routes require login (or require certain user role)
- There might be unsaved date on the current page.
In both cases, a common solution is to intercept requests to change the page, and warn the user that the requested page 1) requires different credentials, or 2) moving to the request page will cause loosing all unsaved data. Depending on the user feedback, one can either continue with the request action and change to the new URL anyway, or abort the navigation.
I know crossroads.js provides callbacks for this, and durandal's router requires usage of objects that support lifecycle (i.e. assumes callbacks have properties for canActivate, canDeactivate, etc.. which are called when jumping from one page to another). I believe sammy.js has similar functionality through its before and after callbacks, and so does Flatiron's director.
What is the right way to deal with this in page.js?
PS: I am looking for a small routing solution that does what is supposed to do an stays out of the way, it seems the only real contenders are page.js and crossroads.js, but crossroads.js hasn't seen a commit in a year, so I was hoping to use page.js. Suggestions for other alternatives are welcome.
oh, better late than never :D
I have an idia with auth middleware like passport.js, that extend ctx:
// auth middleware
page(function (ctx, next) {
ctx.auth = function () {
return !Math.round(Math.random());
};
next();
});
// unsaved data prompt
page(function (ctx, next) {
// pass to the next middleware only on accept
prompt('Are you going to lose all your work?') && next();
});
// usage auth
page(function (ctx, next) {
if (!ctx.auth()) { return; }
// do super secret work here
});
Oh, sorry. PageJS always push history state. That's problem.
I'm poking through the code now. Maybe separate the exits and route callbacks to either side of the history push, and ensure that interruption of exits also intercepts the push?
This seems to intersect somewhat with #193. I'm going to look at fixing both.