JavaScript Routes

Overview

Build Status


Crossroads - JavaScript Routes

Introduction

Crossroads.js is a routing library inspired by URL Route/Dispatch utilities present on frameworks like Rails, Pyramid, Django, CakePHP, CodeIgniter, etc... It parses a string input and decides which action should be executed by matching the string against multiple patterns.

If used properly it can reduce code complexity by decoupling objects and also by abstracting navigation paths.

See project page for documentation and more details.

Links

Dependencies

This library requires JS-Signals to work.

License

MIT License

Distribution Files

Files inside dist folder.

  • crossroads.js : Uncompressed source code with comments.
  • crossroads.min.js : Compressed code.

You can install Crossroads on Node.js using NPM

npm install crossroads

Repository Structure

Folder Structure

dev       ->  development files
|- lib          ->  3rd-party libraries
|- src          ->  source files
|- tests        ->  unit tests
dist      ->  distribution files

Branches

master      ->  always contain code from the latest stable version
release-**  ->  code canditate for the next stable version (alpha/beta)
dev         ->  main development branch (nightly)
gh-pages    ->  project page
**other**   ->  features/hotfixes/experimental, probably non-stable code

Building your own

This project uses Node.js for the build process. If for some reason you need to build a custom version install Node.js and run:

node build

This will delete all JS files inside the dist folder, merge/update/compress source files and copy the output to the dist folder.

IMPORTANT: dist folder always contain the latest version, regular users should not need to run build task.

Running unit tests

On the browser

Open dev/tests/spec_runner-dist.html on your browser.

spec_runner-dist tests dist/crossroads.js and spec_runner-dev tests files inside dev/src - they all run the same specs.

On Node.js

Install npm and run:

npm install --dev
npm test

Each time you run npm test the files inside the dist folder will be updated (it executes node build as a pretest script).

Comments
  • improve the routed/matched dispatch behavior when parsing same request multiple times in a row

    improve the routed/matched dispatch behavior when parsing same request multiple times in a row

    right now the crossroads.routed dispatches on any match even if multiple parse() for same value are called in a row, I'm wondering what would be the correct behavior... Right now I think the correct behavior would be to only dispatch routed if it actually matched a different route than previous time, another option is to create a separate signal with the different behavior (maybe a matched or switched signal).

    enhancement question 
    opened by millermedeiros 13
  • Named Optional Parameters

    Named Optional Parameters

    The Problem

    When there are a series of multiple optional parameters in a route, like these:

    /used-cars/:year:/:make:/:model:
    /recipes/:search-term:/:with-ingredients:
    

    Crossroads cannot treat these optional parameters as fully independent, otherwise routes would be ambiguous. For the first route, constraints on what year, make and model could be possible, but in the 2nd it is not as the domains of their values overlap

    The Solution

    Create optional parameters that also match an identifier so that it can disambiguate exactly what the value is intended to map to. So the previous routes can be written like

    /used-cars/|year|/|make|/|model|
    /recipes/|search-term|/|with-ingredients|
    

    and will match routes like:

    /used-cars/make/ford
    /used-cars/year/2005
    /used-cars/make/toyota/model/tundra
    /recipes/with-ingredients/cheddar
    /recipes/search-term/pasta/with-ingredients/cheddar
    

    This scenario is quite common in when building a filter upon a resource.

    I also cleaned up parse.spec.js a bit as some of the tests could have resulted in false positives if the matching signal callback was called twice, and the first was wrong but the 2nd call was correct.

    feature 
    opened by nathanboktae 12
  • query string support

    query string support

    right now crossroads.js is flexible enough to change the data format but still requires some repetitive work to parse query strings...

    see: https://github.com/auchenberg/crossroads.js/commit/89fb9c14931d052c25b3a6a34dfe0503709e71cf for more info

    still unsure how it should be implemented since in some cases the query string may need to be considered as part of a path segment...

    feature question 
    opened by millermedeiros 10
  • Hashing error with hasher.js

    Hashing error with hasher.js

    The second call to setHash throws an error:

    crossroads.addRoute( 'lorem/{id}', function( id ) { alert( id ); } );
    
    hasher.changed.add( crossroads.parse, crossroads );
    hasher.init();
    
    hasher.setHash('lorem/123');  // works with alert(123)
    hasher.setHash('lorem/456');  // javascript error
    
    opened by JasonKStevens 8
  • should crossroads be case insensitive?

    should crossroads be case insensitive?

    the issue #49 made me think about it:

    1. should routes also be case insensitive? so the route foo/bar would be the same as Foo/BAR.
    2. should crossroads always pass values as lowercase to listeners? (this might cause issues with the query string feature and may be undesirable)

    PS: for now I will implement it as a branch but not merge it into master..

    feature question 
    opened by millermedeiros 7
  • Add support for nested routes

    Add support for nested routes

    Basically it wanted to use crossroads to write something like this.

    todosRoute = crossroads.addRoute('/todos', showStats)
    todosRoute.addRoute('', showAllTasks)
    todosRoute.addRoute('/{id}', showSingleTask)
    

    This matches both /todos and /todos/3. In the first case it shows all tasks, and in the latter it shows only the task with id 3. Additionally it shows the stats in both cases.

    Everything nested routes can do should be specified in nested.spec.js. I will also add documentation.

    opened by geigerzaehler 6
  • Routing on Page Load

    Routing on Page Load

    This is a question, not a bug.

    What is the standard for routing on page load? If I type .com/about/ , I'd like to be routed to .com/#!/about/.

    I've got this working on link click by parsing the href, but I'm not sure about how to do this on page load. Does this need to be configured at the server level?

    question 
    opened by damonbauer 6
  • Route rule that is an array seems to do a case sensitive match against route.

    Route rule that is an array seems to do a case sensitive match against route.

    I noticed if you define a rule that is an array of acceptable values on a route, the matching algorithim in crossroads does a case sensitive match against the the acceptable values. Is this the expected behavior? I would assume such a match would be case insensitive. It also doesn't mention anything about case sensitivity in your documentation.

    var route = crossroads.addRoute("/{controller}/:action:", function(controller, action) {
        // do stuff...
    });
    
    router.rules = {
        controller: ["testcontroller"]
    }
    
    crossroads.parse("/TestController/action");
    

    Thanks for writing this library. It's been a great help!

    enhancement 
    opened by ducka 6
  • how to respond if request bypassed ?

    how to respond if request bypassed ?

    Bypassed action is called each time crossroads can't match any route. Crossroads passes requestString parameter to the action and I can't do anything except logging. Is there any ability to send 404 or close connection? I think it would be great to have response and request objects available in the "bypassed" action.

    enhancement 
    opened by nick7ikin 6
  • How about {id?} instead of :id: convention for an optional parameter

    How about {id?} instead of :id: convention for an optional parameter

    {controller}/{action}/{id?} - ? sign marks the id parameter as optional. {controller}/{action}/{id*} - * implies that the id parameter can contain the rest of the path (all symbols including /)

    opened by koistya 6
  • Trigger Route by name passing arguments

    Trigger Route by name passing arguments

    Hi,

    Your lib is quite good, I have a feature-request: I think it will be cool to create method crossroads.create({ name: "ROUTE_NAME", params: { userId: 4 } }) --> this should call crossroads.parse(CREATED_LOCATION);

    What do you think about this?

    feature invalid 
    opened by milworm 6
  • [ SUGGESTION ] .routed.addBefore() and .routed.addAfter()

    [ SUGGESTION ] .routed.addBefore() and .routed.addAfter()

    I'm using the lib and an insight came up, is there any way to add events before and after a route is dispatched?

    I didn't find in the examples how to do this, do you think it's a good idea to implement this feature?

    opened by nicxlau 0
  • Crossroads - 404 on route

    Crossroads - 404 on route

    Hi! I'm trying to start using crossroads. I've managed to get "/" route working but for some reason others (/account) wont work. Could you help a noobie out of this? `

      var defaultRoute = crossroads.addRoute("/", function () {
    
        $("#root").load("main.html");
    
      });
    
      var accountRoute = crossroads.addRoute("account", function () {
    
        $("#root").load("account.html");
    
      });
      crossroads.parse(document.location.pathname);
    

    `

    I'm getting on url localhost:8000/ all working as I want to but on localhost:8000/account it gives 404... :(

    opened by virtapoika 1
  • Empty url in rules

    Empty url in rules

    Hi, (sorry for my English) I've this code: route ('/{index}' ,'index-page','../views/index', { index:['','home'] })

    it return to me a obj valid to register routes, and work fine, but, if i add a empty url { index:["","home"] } the #home works, but the first index not, because its empty. So how can i add a empty value for my home page? I did not want create a new route for solve this problem... i trying add '/' , '#' but it does not work as it should.

    Obs.: i use some like this ':rest*:', "404", "../views/notFound/on404" to not found page and all my routes works

    thanks for attention (REALLY sorry for my English haha)

    opened by vinibeloni 0
  • Trailing slashes are appended to routes that have query params

    Trailing slashes are appended to routes that have query params

    Route in form of:

    /{foo}{?query}
    /{foo}:?query:
    

    Would end up being interpolated as /foo/?params which is unexpected to happen because trailing slash carries meaning for REST servers.

    opened by ergo 1
Owner
Miller Medeiros
started to make websites for fun and never stopped
Miller Medeiros
a tiny and isomorphic URL router for JavaScript

Synopsis Director is a router. Routing is the process of determining what code to run when a URL is requested. Motivation A routing library that works

a decoupled application framework 5.6k Dec 28, 2022
RESTful degradable JavaScript routing using pushState

Davis.js Description Davis.js is a small JavaScript library using HTML5 history.pushState that allows simple Sinatra style routing for your JavaScript

Oliver Nightingale 532 Sep 24, 2022
JavaScript Routes

Introduction Crossroads.js is a routing library inspired by URL Route/Dispatch utilities present on frameworks like Rails, Pyramid, Django, CakePHP, C

Miller Medeiros 1.4k Oct 22, 2022
Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.

http-fake-backend Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes. It actually can serve

Micromata GmbH 279 Dec 11, 2022
great circle routes in javascript

arc.js Calculate great circles routes as lines in GeoJSON or WKT format. Algorithms from https://edwilliams.org/avform.htm#Intermediate Includes basic

Dane Springmeyer 341 Dec 26, 2022
Single Page Application micro framework. Views, routes and controllers in 60 lines of code

SPApp Single Page Application Micro Framework Supports views, controllers and routing in 60 lines of code! Introduction If you heard anything about MV

Andrew 262 Nov 23, 2022
Avoid CORS issues by using API Routes from Next.js

CORS Demo Avoid CORS issues by using API Routes from Next.js. Get Started Clone the repo git clone [email protected]:gregrickaby/cors-demo.git CD into co

Greg Rickaby 2 Sep 30, 2022
a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense r

Pasecinic Nichita 12 Dec 3, 2022
🛣️ A beautiful `list:routes` for AdonisJS

Pretty List Routes ??️ A beautiful `list:routes` for your AdonisJS application. Installation npm install pretty-list-routes node ace configure pretty-

Julien Ripouteau 24 Jul 16, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
🚏 Routes for Next.js

next-route-map ?? next-route-map allows you to define a route map. It automatically generates page modules that forward original modules in build time

Suyeol Jeon 26 Sep 24, 2022
🔄 Basic project to start studying React and Typescript. With it you can translate text to binary or morse language. This project addresses the creation of routes and components.

max-conversion Projeto criado para iniciar nos estudos de React e Typescript Basic project to gain knowledge in react Na plataforma é possível convert

Igor Neves 3 Feb 12, 2022
API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

null 3 Mar 6, 2022
🛰 Shared component across routes with animations

Shared Vue component across routes with animations Live Demo Why? It's quite common you might have a same component used in different routes (pages) w

Anthony Fu 1.5k Jan 4, 2023
SafeCycle—a tool that keeps cyclists safe. Gone are days of weaving through busy city streets, SafeCycle finds all the bike routes for you to ensure a smooth ride wherever you want to go.

Inspiration Biking—an everyday form of travel for students and professionals across the globe. On-campus, back home, and with the people that we know

Ryan Hu 2 May 2, 2022
generate pages from markdown files with dynamic routes, 0 effort, 0 boilerplate.

next-markdown Markdown Pages for Next.js Dynamic Routes. Blog Aware. Design Your Layout Made for people having a nextjs project in ❤️ with markdown wh

François Rouault 105 Oct 11, 2022
next-graphql-server is a library for building production-grade GraphQL servers using Next.js with API Routes

next-graphql-server next-graphql-server is an easy to use Next.js library for creating performant GraphQL endpoints on top of Next.js API Routes. Star

Jakub Neander 82 Nov 21, 2022
This plugin can be embedded in PHP application to give the web application specific routes/href

Routes Plugin PHP This plugin can be embedded in PHP application to give the web application specific routes/href location and for entering specific/l

Ifechukwudeni Oweh 7 Jul 17, 2022
Ready-to-use Remix + Tailwind CSS routes and components.

remix-blocks What is RemixBlocks? Ready-to-use Remix + Tailwind CSS routes, and UI components, all blocks: Are full-stack routes. Are independent of e

Alexandro Martínez 111 Jan 5, 2023
Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun Bakery Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime. Quick

Dennis Dudek 44 Dec 6, 2022