Search code examples
javascriptjqueryframeworksurl-routing

Express-like routing for client-side Javascript


I am writing some Javascript and I need to add a routing system, otherwise it would be tricky to manage as the list grows.

The Angular routing is good, but I don't want to add it as a dependency. What are the options?

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
}

Solution

  • I ended writing a simple one as follows, it takes a regex string for path

    /**
     * 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();