【问题标题】:Simple Backbone.js Router? (page hierarchy + query string)简单的 Backbone.js 路由器? (页面层次结构+查询字符串)
【发布时间】:2011-11-21 09:32:25
【问题描述】:
如何设置可以处理以下 URL 的 Backbone 路由器:
example.com/#!/story-1/?a=1&b=2
或者最好支持子页面 URL:
example.com/#!/chapter-1/story-1/?a=1&b=2
我基本上想要一种简单的方法来定义具有关联查询字符串的页面。
这是默认支持的还是我应该使用这个或其他附加功能?
https://github.com/documentcloud/backbone/pull/668
最终结果应该是这样的:
请求的资源:
example.com/#!/chapter-1/story-1/?a=1&b=2
解析并查看它是否与 pages 对象中的 page 匹配:
页数:{
Chapter-1_story-1:{
模板:#template1
}
}
使用查询字符串加载页面模板和页面控制器:
PageController.load(template, params)
【问题讨论】:
标签:
javascript
backbone.js
query-string
client-side
router
【解决方案2】:
来自文档:
For example, a route of "search/:query/p:page" will match a fragment of
#search/obama/p2, passing "obama" and "2" to the action. A route of
"file/*path" will match #file/nested/folder/file.txt, passing
"nested/folder/file.txt" to the action.
因此,您可以使用如下变量:
routes:{
'search/:query/:page': 'handlePages'
}
或这样的路径:
routes:{
'search/*path': 'handlePages'
}
我不知道任何查询字符串处理。
【解决方案3】:
您可能需要绘制另一条包含“?”的路线以及伪 url 参数的 splat。例如,这是一个您可以扩展 Router 的函数,它将遍历您的 routes 对象并为每个带有查询字符串的路由绘制一个额外的路由。它还将解析 url 参数并将它们作为最终参数传递给路由方法。
mapRoutesWithParams: function() {
_.each(_.keys(this.routes), function(route) {
this.route(route+'?*params', // draw the route with a query string
this.routes[route],
function() {
var args = _.toArray(arguments);
var params = args.pop();
var paramsObject = _(params.split('&')).reduce(function(memo, pair) {
memo[pair.split('=')[0]] = pair.split('=')[1]; return memo;
}, {});
return this[this.routes[route]].apply(this, args.concat(paramsObject));
}
);
}, this);
}