导航与路径查询字符串 [英] navigate route with querystring

查看:118
本文介绍了导航与路径查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

威尔 Backbone.Router.navigate 设置测试真正

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);

例如,将帖子?富= 3 片段将匹配帖子按默认路由,或者我有来为另一条路线,例如:<?code>职位*查询字符串

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:我知道有存在骨干查询参数,但我想知道的只是骨干。

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

下面的现场演示在行动中看到的code。

Here's a live demo to see the code in action.

这篇关于导航与路径查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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