backbone 学习之Router

Router 为客户端路由提供了许多方法,并能连接到指定的动作(actions)和事件(events)。 对于不支持 History API 的旧浏览器,路由提供了优雅的回调函数并可以透明的进行 URL 片段的转换。

页面加载期间,当应用已经创建了所有的路由,需要调用 Backbone.history.start(),或 Backbone.history.start({pushState : true}) 来确保驱动初始化 URL 的路由。

关于history详解,可见backbone 学习之history

源码:

// Backbone.Router
  // ---------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;// 键值对式的导航规则 映射到处理函数上
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var optionalParam = /\((.*?)\)/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    // 导航 指定路由规则 和routes的效果相同 规则也一样
    route: function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route); // 规则验证
      if (_.isFunction(name)) {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      Backbone.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        callback && callback.apply(router, args);
        router.trigger.apply(router, ['route:' + name].concat(args));
        // 触发router的route事件
        router.trigger('route', name, args);
        // 触发history的route事件
        Backbone.history.trigger('route', router, name, args);
      });
      return this;
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    // 绑定所有的routes
    _bindRoutes: function() {
      if (!this.routes) return;
      this.routes = _.result(this, 'routes');
      var route, routes = _.keys(this.routes);
      while ((route = routes.pop()) != null) {
        this.route(route, this.routes[route]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    // 将route字符串转成正则表达式 
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&') // 将 - { } [ ] + ? . , \ ^ $ # 空格 等进行转义
                   .replace(optionalParam, '(?:$1)?') // 规则中的括号部分 也就是可有可没有的部分
                   .replace(namedParam, function(match, optional){ // 将不带括号部分的 但是:...形式的进行替换可以匹配为非/以外任意字符
                     return optional ? match : '([^\/]+)';
                   })// 
                   .replace(splatParam, '(.*?)');// 将*...形式的替换为除换行以外的任何字符匹配.*
      return new RegExp('^' + route + '$'); // 构建正则 加上 开始^和结束$
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted decoded parameters. Empty or unmatched parameters will be
    // treated as `null` to normalize cross-browser behavior.
    // 返回decode后的一些URL信息(通过和route匹配的fragment做处理)
    _extractParameters: function(route, fragment) {
      var params = route.exec(fragment).slice(1);
      return _.map(params, function(param) {
        return param ? decodeURIComponent(param) : null;
      });
    }

  });

欢迎指导、纠错、建议。

原文地址:https://www.cnblogs.com/xiaobudiandian/p/Backbone_router.html