【发布时间】:2012-02-13 13:12:12
【问题描述】:
所以我需要删除backbone.js 中的路由器以防止其路由发生。我试过myRouter.off() 和myRouter.remove() 没有任何运气。
我能做些什么呢?
【问题讨论】:
标签: backbone.js unbind
所以我需要删除backbone.js 中的路由器以防止其路由发生。我试过myRouter.off() 和myRouter.remove() 没有任何运气。
我能做些什么呢?
【问题讨论】:
标签: backbone.js unbind
没有官方支持的方式来做到这一点(据我所知)。如果你想禁用 any 路由器,你可以使用Backbone.history.stop();,它没有被记录,但是在源代码中显示了这个注释:
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
否则,如果路由器的状态为“禁用”或类似情况,您必须在路由器的路由处理程序中编写一些直通条件。或者迭代未记录的 Backbone.history.handlers(包含 .route - 作为正则表达式和 .callback 的内部数组)并删除与此特定路由器相关的路由。
显然,由于没有记录,这可能会在 Backbone 的未来版本中发生变化。
【讨论】:
如果您能够控制路由器的实例化,您可以执行以下操作:
var myRouter = new MyRouter({ routes: function(){
return;
}});
【讨论】:
您可以使用基于 hack 的解决方案(它使用非 API 方法,并且可能会停止使用新版本的 Backbone.js)
var router = new(Backbone.Router.extend({
routes: {
"authentication": "authentication",
"contacts": "contacts",
"*notFound": "notFound"
},
/**
* @param {string} routeName
*/
disableRoute: function(routeName) {
var index, handler, handlers = Backbone.history.handlers;
delete this.routes[routeName];
for (var i = 0, len = handlers.length; i < len; i++) {
handler = handlers[i];
if (handler.route.toString() === router._routeToRegExp(routeName).toString()) {
handlers.splice(index, 1);
break;
}
}
},
contacts: function() {
alert('route `contacts`');
},
authentication: function() {
alert('route `authentication`');
},
notFound: function() {
alert('route `notFound`');
router.navigate('404');
}
}));
Backbone.history.start({
silent: true
});
$(function() {
$('#remove').on('click', function() {
router.disableRoute('authentication');
router.navigate('404');
});
$('#goto_auth').on('click', function() {
router.navigate('authentication', {
trigger: true
});
});
$('#goto_contacts').on('click', function() {
router.navigate('contacts', {
trigger: true
});
});
});
button {
display: block;
margin: 10px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
</head>
<body>
<button id="goto_auth">goto authentication route</button>
<button id="goto_contacts">goto contacts route</button>
<hr>
<button id="remove">remove authentication route</button>
</body>
</html>
【讨论】: