Javascript Backbone.History.extend({loadUrl:…})为有效路由返回false
我正在尝试扩展Backbone.History.loadUrl()以捕获404错误:Javascript Backbone.History.extend({loadUrl:…})为有效路由返回false,javascript,backbone.js,marionette,backbone-routing,Javascript,Backbone.js,Marionette,Backbone Routing,我正在尝试扩展Backbone.History.loadUrl()以捕获404错误: var History = Backbone.History.extend({ loadUrl: function() { var match = Backbone.History.prototype.loadUrl.apply(this, arguments); if (!match) { console.log(
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();
这是基于此处建议的解决方案:
我遇到的问题是,当我在有效路由上调用(Backbone.history=new history).start()
时,它返回false。但是,当我在同一个路由上调用Backbone.history.start()
时,它返回true
当我向extended 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()
ing历史记录之前实例化路由器或添加路由处理程序:
Backbone.history = new History();
// either
new CustomRouter();
// or
Backbone.history.route(/^some-route/, function(){ console.log("at test-login"); })
history.start();
我怀疑您在重新装入并启动历史记录实例之后,没有向历史记录中添加一些路由处理程序(通过调用
主干.history.route()
或在启动历史记录之前创建路由器
实例)。请逐步完成代码,并在start()
方法的末尾停止,进入loadUrl()
并检查它是否实际针对处理程序列表进行测试。事实上,如果您确实编写了(Backbone.history=new history).start()代码>,当start()
运行时,您一定会错过路由处理程序。您能稍微解释一下这个解决方案吗?我是个笨蛋。