Backbone router failing to respect trigger=false option
-
17-06-2021 - |
Question
Backbone.js provides a navigate(fragment, [options])
method for its Backbone.router objects, which does the following (per the documentation):
Whenever you reach a point in your application that you'd like to save as a URL, call
navigate
in order to update the URL. If you wish to also call the route function, set thetrigger
option totrue
. To update the URL without creating an entry in the browser's history, set thereplace
option totrue
.
Thus, simply calling appRouter.navigate('page');
would presumably change the URL to www.myapp.com/page
without triggering the corresponding route. However, I'm finding that my router redirects to the URL and also triggers the page route, despite the fact that trigger=false
by default.
Thus, the following code:
$(function(){
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'page': 'page',
},
home: function() {
window.app.navigate('page', {replace: true});
console.log('home route');
},
page: function () {
console.log('page route');
},
});
window.app = new AppRouter();
Backbone.history.start({pushState: true});
});
produces the following console output when navigating to www.myapp.com:
> home route
> page route
when the expected console output should just be:
> home route
The method seems to be disobeying the default trigger
option. Is this a bug in the implementation, or am I misunderstanding something?
Solution
Updating to the latest version of Backbone as of 6/28/12 (the master version on https://github.com/documentcloud/backbone) resolves the issue.
OTHER TIPS
Take off the pushState: true
from the Backbone.history.start
and try it with the original navigate
call.
I googled around for a solution to this, but all I got was vague remarks about the history API's pushState: true
causing the Backbone Router's navigate function not to work properly. For an example of my Googlings this striked out article was about the best resource on the matter I could find.