Backbone.History.扩展({loadUrl: ..})对于有效路由返回false

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

本文关键字:于有效 有效 路由 false 返回 扩展 History loadUrl Backbone      更新时间:2023-09-26

我正在尝试扩展Backbone.History.loadUrl()来捕获404错误:

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();

这是基于这里建议的解决方案:https://github.com/jashkenas/backbone/issues/308#issuecomment-9482299.

我遇到的问题是,当我在有效路由上调用(Backbone.history = new History).start()时,它返回false。然而,当我在同一路由上调用Backbone.history.start()时,它返回true。

当我在扩展loadUrl方法中添加调试器时,match被设置为false。

你知道是什么导致了差异吗?

这个应该可以。

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;
  }
});

如果你真的写

(Backbone.history = new History).start();

你的新历史实例没有任何路由处理程序。因此,它在开始时不会匹配任何通往false的路线。当你在start()之后添加处理程序,然后导航到该路由,它当然会触发true

你应该在start()历史记录之前实例化你的路由器或添加路由处理程序:

Backbone.history = new History();
// either 
new CustomRouter();
// or
Backbone.history.route(/^some-route/, function(){ console.log("at test-login"); })
history.start();