2

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?

Francine
  • 51
  • 1
  • 2
  • I suspect you've missed to add some route handlers to the history (by either calling `Backbone.history.route()` or creating a `Router` instance before starting the history) after re-crating and starting the history instance. Please step through the code and stop at the end of the `start()` method, step into `loadUrl()` and check if it's actually testing against a list of handlers. – try-catch-finally Oct 15 '15 at 21:25
  • In fact, if you literally write `(Backbone.history = new History).start();`, you must miss route handlers when `start()` runs. – try-catch-finally Oct 15 '15 at 21:40

2 Answers2

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;
  }
});
Andrew Hubbs
  • 9,338
  • 9
  • 48
  • 71
0

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();
try-catch-finally
  • 7,436
  • 6
  • 46
  • 67