As I work through the last of the issues before the release of Recipes with Backbone, I make a quick post to keep the god of my chain appeased.
With regards to the route redirection with which I was fiddling last night, my co-author, Nick Gauthier suggested that I try an alternative approach. Specifically, my default route is currently manually navigating to the correct push state location for my App:
var Routes = Backbone.Router.extend({
// ...
routes: {
"": "setDefault",
"page/:page": "page"
},
setDefault: function() {
Backbone.history.navigate("#page/" + this.paginator.page());
},
// ...
});
However, the original empty route prior to the redirect in setDefault
remains in browser history (at least in some browsers). This means that the Back button is effectively broken—clicking Back will always hit the empty route in the browser history which redirects.Nick's suggestion was to do away with the
setDefault()
router method. Instead, he suggests mapping the empty route directly to the page()
route method: var Routes = Backbone.Router.extend({
// ...
routes: {
"": "page",
"page/:page": "page"
},
// ...
page: function(page) {
if (typeof(page) == "undefined") page = 0;
this.paginator.page(page);
this.paginator.render();
}
});
The only change I then need to make is to teach the page()
method what to do when page is not set (e.g. in the URL page/2
). As can be seen above, I set the default page to zero.And that works. Even clicking the Back button keeps the URL and the pagination controls in sync:
So ultimately, the solution is to not attempt router redirection. Still, we have some decent workarounds in the book (in addition to the above).
I call it a day here and am going to get back to proof reading. So tired....
Day #221
No comments:
Post a Comment