我试图覆盖路由功能Backbone.Router,这是我的代码:
router.js
(function($, Backbone, _, app){
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home'
},
initialize: function (options) {
Backbone.history.start();
},
route: function (route, name, callback) {
var router = this;
if (!callback) callback = router[name];
var f = function() {
console.log("route before", route);
callback.apply(router, arguments);
console.log("route after", route);
}
return Backbone.Router.prototype.route.call(router, route, name, f);
}
});
app.router = AppRouter;
})(jQuery, Backbone, _, app);
app.js
var app = (function($){
var config = $('#config'),
app = JSON.parse(config.text());
$(document).ready(function(){
var router = new app.router();
});
return app;
})(jQuery);
的index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="{% static 'js/jquery.js' %}" type="text/javascript"></script>
<script src="{% static 'js/bootstrap.min.js' %}" type="text/javascript"></script>
<script src="{% static 'js/bootstrap.js' %}" type="text/javascript"></script>
<script src="{% static 'js/underscore.js' %}" type="text/javascript"></script>
<script src="{% static 'js/backbone.js' %}" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.min.js"></script>
<!--App js-->
<script id="config" type="text/json">
{
"models": {},
"collections": {},
"views": {},
"router": null,
"apiRoot": "{% url 'api-root' %}",
"apiLogin": "{% url 'api-token' %}"
}
</script>
<script src="{% static 'app-js/app.js' %}"></script>
<script src="{% static 'app-js/models.js' %}"></script>
<script src="{% static 'app-js/views.js' %}"></script>
<script src="{% static 'app-js/router.js' %}"></script>
</body>
</html>
但是,&#39;之前&#39;和&#39;之后&#39;没有打印在控制台上。
我正在关注http://jsfiddle.net/nikoshr/EdLzh/
上的代码在控制台上打印之前和之后。
我还尝试更换父母的路线&#39;
Backbone.Router.prototype.route.call(router, route, name, f);
与
AppRouter.__super__.route.apply(router, [route, name, callback]);
但是函数f仍未被调用。
我也尝试用
替换相同的语句Backbone.Router.prototype.route.apply(router, [route, name, f]);
以及
Backbone.Router.prototype.route.apply(this, [route, name, f]);
以及
Backbone.Router.prototype.route.callback(this, route, name, f);
但是仍然没有在浏览器的控制台中调用函数f。
请帮忙。
答案 0 :(得分:1)
首先,您的路由器没有设置home
回调,但覆盖假设此回调存在,并在执行时以错误结束。
尝试添加安全措施,例如
route: function (route, name, callback) {
var router = this;
if (!callback) callback = router[name];
// adds a default function that will intercept the missing callbacks
if (!callback) {
callback = function() {
console.log('Route ' + name + ' not defined');
}
}
var f = function() {
console.log("route before", route);
callback.apply(router, arguments);
console.log("route after", route);
}
return Backbone.Router.prototype.route.call(router, route, name, f);
}
演示http://jsfiddle.net/nikoshr/a78n9rj1/2/
第二,请注意必须通过routes
哈希或Router.route
来定义路由,以便在该函数中发生某些事情,它不会捕获所有哈希更改。