Backbone.History.extend( { loadUrl: …} ) returning false for valid routes

落花浮王杯 提交于 2019-12-11 03:31:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!