客户端类似 Express 的路由 Javascript

Express-like routing for client-side Javascript

我正在写一些Javascript,我需要添加一个路由系统,否则随着列表的增长管理起来会很棘手。

Angular 路由很好,但我不想将其添加为依赖项。有哪些选择?

if(window.location.pathname==='/') {
  var $btn = $('<a />').html('btn').click(function() {
    $questionList.html(findAnswers());
  });
  $tabs.prepend($btn);
}

if(window.location.pathname==='/posts') {
  // some code will run when only on post page
}

RouterJS and HistoryJS 看起来他们可能会满足您的需求。

我写了一个简单的如下,它需要一个正则表达式字符串作为路径

/**
 * routing for client side code in express style
 */
var expressRouting = function() {
  var path = window.location.pathname;
  var mapping = {};

  function get(url, callback) {
    mapping[url] = callback;
  };

  function listen() {
    Object.keys(mapping).forEach(function(key) {
      var regexp = new RegExp(key);
      if(regexp.test(path)) {
        var method = mapping[key];
        if(method) {
          method.call(this);
        }
      }
    });
  };

  return {
    debug : mapping,
    path : path,
    get : get,
    listen : listen
  }
};

// usage

var myapp = expressRouting();

myapp.get('/$', function() {
  alert('Hey, only on the homepage')
});

myapp.get('/questions$', function() {
  alert('Hey, only on the questions page')
});

myapp.listen();