在backbone.js中取消绑定路由器
问题描述:
因此我需要删除backbone.js
中的路由器以防止发生路由。我试过myRouter.off()
和myRouter.remove()
没有任何运气。在backbone.js中取消绑定路由器
我能做些什么呢?
答
有没有官方支持的方式来做到这一点(我知道)。如果要禁用任何路由器,您可以使用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),并删除与此特定路由器相关的路由。
显然,无证和所有,这在未来的骨干版本中可能会发生变化。
答
,如果你能控制你的路由器的实例,你可以做到以下几点:
var myRouter = new MyRouter({ routes: function(){
return;
}});
答
您可以使用黑客为主的解决方案(它使用非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>
有趣的),我想注销的应用程序是非常有用的后禁用它,还有其他的方式来处理我吨,但我真的很喜欢backbone.history.stop – pushplaybang 2014-03-31 11:02:28