问题
I'm trying to extend Backbone.History.loadUrl() to catch 404 errors:
var History = Backbone.History.extend({
loadUrl: function() {
var match = Backbone.History.prototype.loadUrl.apply(this, arguments);
if (!match) {
console.log('route not found');
}
return match;
}
});
(Backbone.history = new History).start();
This is based on the solution suggested here: https://github.com/jashkenas/backbone/issues/308#issuecomment-9482299.
The problem I'm encountering is that when I call (Backbone.history = new History).start()
on a valid route, it returns false. However, when I call Backbone.history.start()
on the same route, it returns true.
When I add a debugger to the extended loadUrl method, match
is set to false.
Any ideas about what's causing the discrepancy?
回答1:
This should work instead.
var oldLoadUrl = Backbone.History.prototype.loadUrl;
_.extend(Backbone.History.prototype, {
loadUrl : function () {
var matched = oldLoadUrl.apply(this, arguments);
if (!matched) {
console.log('route not found');
}
return matched;
}
});
回答2:
If you literally write
(Backbone.history = new History).start();
your new History instance does not have any route handler. Thus it won't match any route at start leading to false
. When you add handlers after start()
and then navigate to that route it will trigger true
of course.
You should either instantiate your router or add route handlers before start()
ing the history:
Backbone.history = new History();
// either
new CustomRouter();
// or
Backbone.history.route(/^some-route/, function(){ console.log("at test-login"); })
history.start();
来源:https://stackoverflow.com/questions/33151326/backbone-history-extend-loadurl-returning-false-for-valid-routes