使用查询字符串导航路线 [英] navigate route with querystring
本文介绍了使用查询字符串导航路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将 Backbone.Router.navigate
设置 test
为 true
:
var test = false;
var Router = Backbone.Router.extend({
routes: {
'posts': 'showPosts'
},
showPosts: function () {
test = true;
}
});
router = new Router();
Backbone.history.start();
router.navigate('posts?foo=3', {trigger: true});
assert.ok(test);
例如,posts?foo=3
片段会默认匹配 posts
路由,还是我必须为此设置另一个路由,例如:posts?*querystring
?
Eg, will posts?foo=3
fragment will match the posts
route by default, or do I have to set another route for that, for example: posts?*querystring
?
谢谢
PS:我知道存在 backbone-query-parameters 但我想只知道骨干.
PS: I know there exist the backbone-query-parameters but I want to know just for backbone.
推荐答案
您需要添加另一个带有该参数的路由:
You need to add another route with that expecting parameter :
routes: {
'posts?foo=:foo' : 'showPosts',
'posts': 'showPosts'
},
showPosts: function (foo) {
if(typeof foo != 'undefined'){
// foo parameters was passed
}
test = true;
}
更新
您可以定义一般路线以返回所有查询字符串,然后在处理程序中解析它:
update
You could define the general route to return all the query string and then parse it in the handler :
routes: {
'posts': 'showPosts',
'posts?*queryString' : 'showPosts'
},
showPosts: function (queryString) {
var params = parseQueryString(queryString);
if(params.foo){
// foo parameters was passed
}
}
...
// and the function that parses the query string can be something like :
function parseQueryString(queryString){
var params = {};
if(queryString){
_.each(
_.map(decodeURI(queryString).split(/&/g),function(el,i){
var aux = el.split('='), o = {};
if(aux.length >= 1){
var val = undefined;
if(aux.length == 2)
val = aux[1];
o[aux[0]] = val;
}
return o;
}),
function(o){
_.extend(params,o);
}
);
}
return params;
}
更新 2
这是现场演示,可查看代码的运行情况.
Here's a live demo to see the code in action.
这篇关于使用查询字符串导航路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文