是否有可能在Backbone.js路由中有可选参数?Backbone.js路由可选参数
e.g这样的:
routes:
"search/[:query]": "searchIndex"
代替:
routes:
"search/": "searchIndex"
"search/:query": "searchIndex"
是否有可能在Backbone.js路由中有可选参数?Backbone.js路由可选参数
e.g这样的:
routes:
"search/[:query]": "searchIndex"
代替:
routes:
"search/": "searchIndex"
"search/:query": "searchIndex"
从Backbone 0.9.9开始,您可以添加带括号的可选参数。
例如,在你的路由对象,你可以像这样定义一个可选路线部分:
routes: {
"organize(/:action)": "displayOrganize"
}
现在的URL路径将匹配/#organize
和路线像/#organize/create
。
请记住,如果你需要一个像/#organize/
路线(以斜杠)得到认可,你可以这样做:
routes: {
"organize(/)(:action)": "displayOrganize"
}
如何处理displayOrganize中的操作?你可以做'displayOrganize:function(action){if(action){//做些什么...}}'? – 1nfiniti 2013-05-31 14:25:17
这应该是被接受的答案。 – 2015-02-27 13:14:46
有关使用*splat
什么:
路线
router.routes
路由哈希将带有参数的URL映射到路由器上的功能,类似于View的事件哈希。路线可以包含参数部分,
:param
,它们在斜杠之间匹配单个URL组件;和splat部分*splat
,它可以匹配任意数量的URL组件。例如,
"search/:query/p:page"
的路由将匹配#search/obama/p2
的片段,将"obama"
和"2"
传递给该动作。"file/*path"
的路线将匹配#file/nested/folder/file.txt
,将"nested/folder/file.txt"
传递给该操作。
您可以添加使用the route
method手动正则表达式根据路线:
路线
router.route(route, name, [callback])
手动创建路由器的路由,
route
参数可以是路由字符串或正则表达式。来自路由或正则表达式的每个匹配捕获都将作为参数传递给回调。
所以这样的事情应该工作:
this.route(/^search\/(.*)?/, 'searchIndex');
然后searchIndex
将被调用你什么或你的:query
作为其参数。
缺点是你不能把正则表达式路由到你的routes
对象中。如果你想把它们放在一起,你可以在你的路由器的initialize
方法中加入route
的所有路由。
可能是刚刚宣布超过一个航,一有多余的ARG,一个没有最简单的方法:
routes:{
"authProxy/:hash": "authProxy",
"authProxy/:hash/:url": "authProxy"
}
然后只检查他们在你的方法:
authProxy: function(hash, url){
if (url){
// Hash and URL.
}else{
// Just hash.
}
}
注我比其他两个答案要好得多,因为其他开发人员很容易理解发生了什么。
加布轰的答案应该是公认的答案,而不是@mu太短。 – 2015-02-27 13:15:27
是的!技术进步! – TTT 2015-02-27 14:10:04
像“search /:query”这样的路由不适合我。但“搜索”工作正常。任何想法? – 2015-12-16 11:31:18