Git Product home page Git Product logo

simrou's Introduction

Simrou 1.5

A very tiny hash-based JavaScript routing system

Simrou is a small JavaScript framework that allows to bind event handlers that listen to changes of window.location.hash. This is in particular useful when developing single-page web applications, because this technique helps to write maintainable code and enables deep-linking. See the demo code below to get an idea of how this works.

In contrary to other frameworks with similar features, Simrou is intended to be extremly simple to setup and use. It does not provide any other features beside the routing, hence it is very lightweight and flexible.

Demo

// Setup an instance of Simrou
var router = new Simrou();

// Register a route that matches edit requests to any article
var editRoute = router.addRoute('/article/:id/edit');

// Bind an action handler to that route
editRoute.get(function(event, params) {
    showEditForm(params.id);
});

// HTML Forms are getting watched, so you can even bind an
// action handler to POST/PUT/DELETE requests.
editRoute.post(saveChanges);

// Start the engine!
router.start();

// Navigate somewhere (updates location.hash and resolves the URL)
router.navigate('/article/42/edit');

// ..or resolve without touching location.hash
router.resolve('/article/18/edit', 'POST');

Links work just as expected if you prepend them with a hash symbol:

<a href="#/article/182/edit">Edit article 182</a>

A typical url within your application will look like this:

http://your-domain.tld/#/article/182/edit

Advanced usage

Create custom routers with CoffeeScript

Simrou can easily be used as a basis for your own routing classes that encapsulates the specific routing logic for your application or for parts of it.

class MyRouter extends Simrou
    initialize: ->
        # Add some routes
        @addRoute('/articles/:id').get(@getArticle).post(@postArticle)
    
    getArticle: (event, params) ->
        Model.loadArticle params.id
    
    postArticle: (event, params) ->
        # ...

router = new MyRouter
router.start()

Bulk adding of routes

You can add more than one route or action handler at a time:

var router = new Simrou({
    '/article/:id/edit': {
        get: [ actionHandler11, actionHandler12 ],
        post: actionHandler2,
        put: actionHandler3
    },
    '/downloads/*': { get: actionHandler4 },
    '/homepage': actionHandler5
});

router.start('/homepage');   // Handing over a default route to navigate to

Wildcards

You can use two different types of wildcards in your routes: Parameters and Splats (this is just the same as in Backbone.js).

  • Parameters are introduced by a colon and end at the next slash.
    e.g. "/test/:name" matches "/test/mike" and "/test/joe", but not "/test/joe/something".

  • Splats work the same way, but start with an asterix instead of a colon and are not limited by slashes. They are an optional part of the route.
    e.g. "/test/*sp" matches "/test" (extracting ""), "/test/joe" (extracting "joe") and "/test/joe/something/more" (extracting "joe/something/more").

Parameters and splats can be mixed:

var articleRoute = router.addRoute('/articles/:edit/*action');

Any action handler attached to this route will be called with the following arguments:

function actionHandler(event, parameters, method)
  • event is a jQuery event object.
  • parameters is a plain object {} that contains the values extracted from the route (parameters and splats).
    With the route from above example, parameter has two properties, "edit" and "action".
  • method is a string such as 'get' or 'post', specifing the desired HTTP method.

Case-insensitive routes

By default, all routes are case-sensitive. For a situation where you need to create a case-insensitive route, addRoute() accepts a second parameter:

var route = router.addRoute('/foo', false); // <-- route is now case-insensitive, e.g. '/FOO' is a match.

Assembling routes

The route object provides a nifty helper method to get a concrete url:

var article = router.addRoute('/articles/:id/*action');
var url = article.assemble(17, 'edit'); // returns: /articles/17/edit

// Equivalent syntax:
url = article.assemble({ id: 17, action: 'edit' });

Attaching event handlers via jQuery events

Action handlers can be attached via jQuery events instead of using Simrou's attachAction() method or the shortcuts get(), post(), put(), delete() and any():

var route = router.addRoute('some/route');

// This..
$(route).on('simrou:get', eventHandler);

// ..equals:
route.get(eventHandler);

Event handlers for "any" HTTP method

If you want to catch a route regardless which HTTP method was intended, you can do that as well:

route.any(function() {
    // ..do stuff..
});

Note that it is possible to bind multiple event handlers to a route, e.g.:

var route = router.addRoute('some/route');

route.get(eventHandler1);
route.get(eventHandler2);
route.any(eventHandler3);

router.resolve('some/route', 'get'); // all three event handlers get notified!

Requirements & License

Simrou requires jQuery 1.7 or newer and is released under the MIT license.

Internally, Simrou binds itself to the onHashChange event. If you want to include a fallback for older browser or the IE 7, Simrou works out of the box with Ben Alman's excellent HashChange Plugin for jQuery. No setup required.

simrou's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

simrou's Issues

route travel

is there a way to detect where the route travel from and to

eg:

route.travel( '/from', '/to', handler );

NotFound callback support

Our application uses notFound callback to report error as main aim.
Another helpful feature is if page not found try to resolve path externally, for instance load routes dynamically using RequireJs

Enable in IE7

How can simrou be enabled in IE7? The URL is appended but the action handler not called.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of buero-fuer-ideen/Simrou!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library buero-fuer-ideen/Simrou is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "buero-fuer-ideen/Simrou",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

how to do a form post?

i have setup these to listen for post

    route.addRoute('/search/:key') 
            .post(function(e, param){ console.log('things') })

    //   try these methods below in here

    route.start() 
  • i've tried to just use action="#/search/" method="post", it refresh the page
  • than i tried to use route.navigate / route.resolve ; aint working
  • than i've tried to form.on('submit', handler(e)) { e.preventDefault ); nothing happens
  • than i've tried use $.ajax(url : '#/search' + param, type: 'post'); still nothing happens

Just found the handleFormSubmit(e) method, so i put it into

var init = function(route){
     route.addRoute('/search/:key')
             .post(function(e, param){
                    console.log(param.key)
             });

     $('form').on('submit', route.handleFormSubmit );
}

this opens up 2 more new issues,

1- how to parse in the input field data
2- it triggered the function twice, i noticed it calls the _bind method in the stack, which than triggers my init() again


seems like the form post to it without jquery.listener,

which comes down to how to get the data from the field?


i finally got the data pass through using $('form').serialize(), have to use jquery.submit method and return false to do a double trigger and capture the var data before route.post(funciton(){ console.log(data) }) to use.

Doens't seems convenient, hope this will be solved with the other ticket passing data{}, as 2nd param to resolve/navigate/formhandler.

Trailing slash intended behaviour?

I have just noted that overview.html#/homepage/ will be treated differently to overview.html#/homepage.

Just wondering if this is the intended behaviour?

router.start() doesn't work in Safari / Safari mobile

When using router.start('/myroute'); the route is not registered in Safari's history.

To reproduce in demo files navigate to article 172 then click the browser back button.

Expected behaviour: browser goes to overview.html#/homepage

Behaviour in Safari: browser goes to overview.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.