简单的Backbone.js路由器?(页面层次结构+查询字符串)

Simple Backbone.js Router? (page hierarchy + query string)

本文关键字:层次结构 查询 字符串 Backbone js 路由器 简单      更新时间:2023-09-26

我如何建立一个骨干路由器,可以处理url,如:

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

最终结果应该是这样的:

  1. 请求资源:
    example.com/# !/第1章/故事1/? a = 1, b = 2

  2. 解析并查看是否与pages object中的page匹配:
    页面:{Chapter-1_story-1: {模板:#template1}}

  3. 用查询字符串加载页面模板和页面控制器:
    PageController。加载(模板,params)

@jhudson8从pull request #668创建backbone-query-parameters插件

非常简单,只需将backbone.queryparams.js复制到您的环境中,并在backbone.js之后包含

From the docs:

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'
 }

我不知道任何查询字符串处理然而。

您可能需要绘制另一条包含'?'和用于伪url参数的splat。例如,这是一个你可以扩展Router的函数,它将遍历你的routes对象,并为每一个带有查询字符串的路由绘制额外的路由。它还会解析url参数,并将它们作为最后一个参数传递给route方法。

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