有没有办法用 Backbone 捕获所有不匹配的路由? [英] Is there a way to catch all non-matched routes with Backbone?

查看:30
本文介绍了有没有办法用 Backbone 捕获所有不匹配的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个捕获所有"路由,当其他定义的路由都不匹配时运行.一种 404 NotFound 错误处理程序.

I want to have a 'catch all' route which runs when none of the other defined routes are matched. A type of 404 NotFound error handler.

我试过添加这个,它可以工作,但会阻止其他路由匹配:

I've tried adding this, which works but prevents other routes from matching:

this.route(/(.*)/, 'notFound', this.notFound);

以前有人解决过这个问题吗?

Anyone solved this problem before?

推荐答案

为了完整性,请在此处回答.

Answering here for completeness.

您可以通过两种方式做到这一点.使用 route() 定义正则表达式,如问题所示.但是,由于这个错误,您需要通过route()定义所有路由代码> 方法,并以相反的顺序(在顶部捕获).这会阻止您使用路由哈希,因此(我的)首选方法是:

You can do this 2 ways. Define the regular expression using route(), as in the question. However, due to this bug you would need to define all your routes via the route() method, and in reverse order (catchall at top). This prevents you from using the routes hash, so (my) preferred method is:

routes: {
  'users/search': 'searchUsers',
  'users/:id': 'loadUser',

  '*notFound': 'notFound'
}

'*notFound' 实际上可以是任何以 * 开头的东西.您只需要 * 后面的字符来防止解析错误.

The key '*notFound' can actually be anything starting with *. You just require characters after the * to prevent a parsing error.

这篇关于有没有办法用 Backbone 捕获所有不匹配的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆