Code Monkey home page Code Monkey logo

base-router's Introduction

base-router

A simple and portable router for the client and server.

build status NPM version experimental

Sauce Test Status

example

var createRouter = require('base-router')

// Create a router that will resolve data
var router = createRouter({
  '/': function () {
    return [1,2,3]
  }
})

// React to transition events
router.on('transition', function (route, data) {
  // Trigger re-render with virtual dom here
})

// Manually trigger transitioning to routes
router.transtionTo('/')

Specifying Routes

This library uses the module routington to specify and match routes. Please see their docs for route matching.

Some common examples are:

  • /bears will match /bears
  • /bears/:type will match /bears/grizzly
  • /bears/:type? will match /bears or /bears/grizzly

Resolving Data

You can resolve data using return, callback or promise:

var router = createRouter({
  '/': function () {
    // Throw an error to indicate an error
    return [1,2,3]
  },
  '/callback': function (params, done) {
    // Call done with an error as the the first param to indicate an error
    done(null, [1,2,3])
  },
  '/promise': function () {
    return new Promise(function (resolve, reject) {
      // Reject the promise to indicate an error
      resolve([1,2,3])
    })
  },
})

A loading event is emitted indicating the route is transitioning but has not yet finished resolving. Only when the route has resolved will transition be called.

Example with virtual-dom

var createRouter = require('base-router')
var h = require('virtual-dom/h')
var xhr = require('xhr')

var router = createRouter({
  '/': function () {
    // Define simple elements for this route
    return h('div', 'Home Page')
  },
  '/posts/:post': function (params, done) {
    // If remote data is needed grab that
    xhr('/api/posts/' + params.post, function (err, res, body) {
      if (err) return done(err)
      // Then return a vnode with the retrieved data
      done(null, h('.post', body))
    })
  },
})

router.on('transition', function (route, childNode) {
  // Render each page based on the route selected
  var links = [
    h('a', { href: '/' }, 'Home'),
    h('a', { href: '/posts/one' }, 'First Post')
  ]
  var content = h('.content', [links, childNode])
  // Now we can render our page with virtual dom diffing
})

api

var router = new BaseRouter([routes, options])

Creates a new instance of base-router.

  • routes - An object literal of routes to create.
  • options - An object literal to configure:
    • location - Whether to manage the window.location. If window.history.pushState is available it will use that otherwise it will use window.location.hash. Set to false to disable, hash to force using hashes, and history to force using push state.

router.route(name, model)

Adds a new route. name is the pathname to our route and model is a function that resolves the data for the route.

router.route('/user/:id', function (params, done) {
  done(null, params.id)
})

router.transitionTo(name[, params, callback])

Transitions to the given route name.

Optionally you can supply params to override the params given to a route.

Optionally you can supply a callback which will be called instead of using the transition and error events.

router.currentRoute

The last resolved route we are currently on.

Events

.on('transition', function (name, data) {})

When a transition has resolved. Gives the name of the route and the data that has been resolved by the model.

.on('loading', function (name, abort) {})

Indicates the desire to transition into a route with name but model has not yet resolved.

Call abort() to abort the transition.

.on('error', function (name, err) {})

When a transition has errored. Gives the name of the route and the err that has been either thrown, first argument of callback or rejected by the promise.

license

(c) 2015 Kyle Robinson Young. MIT License

base-router's People

Contributors

chinedufn avatar gmaclennan avatar shama avatar yoshuawuyts avatar

Stargazers

 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

base-router's Issues

issue running with yo-yo

Hi @shama I got an issue while following the example to run base-router with yo-yo.

Here's the code http://requirebin.com/?gist=4463cb79b10a06a62e28a294f7ca7013

var yo = require('yo-yo')
var createRouter = require('base-router')

var element = yo`<div></div>`
var app = document.body.appendChild(element)

var router = createRouter({
  '/': function () {
    console.log('home page...')
    return yo`<div>home page</div>`
  },
  '/about': function () {
    console.log('about page...')
    return yo`<div>about page</div>`
  }
}, {
  location: 'hash'
})

router.on('transition', function (route, childNode) {
  yo.update(element, childNode)
})

router.transtionTo('/')

Somehow I always get Uncaught TypeError: router.transtionTo is not a function from the browser at the initial run. But it works if I console the router in the devtool and call router.transtionTo('/') from there.

I've debug it for a while but still don't know what's going wrong here, do I miss something?

Preventing page reload on link click

Right now if you click a link your entire application reloads. Thoughts on having base-router prevent this by default?

Something like:

  if (usePush) {
    function preventLinkReload(e) {
      if (e.target.tagName !== 'A') return
      e.preventDefault()
      self.transitionTo(e.target.pathname)
    }
    document.addEventListener('click', preventLinkReload, false)
    // etc

Will PR if there's interest ;)

route vs addRoute

I'm thinking that Router.route should be deprecated in favor of a new Router.addRoute and removed whenever v2 roles around.

Seems like it might make more sense, especially since base-router is depending on routes for now

Don't push new state onpopstate

Right now base-router calls window.history.pushState whenever window.onpopstate is called.

This should never happen since it duplicates history entries and breaks the back button

Revisit API for serve

Currently .serve() returns a middleware but that makes it a little difficult if you want to integrate with other middleware. Such as:

var useBaseRouter = app.router.serve(function (page, data) {
  app.render(page, data)
  this.response.writeHead(200, { 'Content-Type': 'text/html' })
  this.response.end(toHTML(app.element.vtree))
})
require('http').createServer(function (req, res) {
  if (req.url == 'something else') res.end('Error!')
  else useBaseRouter(req, res)
}).listen(1337)

Also the context with this.response and this.request is a little awkward.

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.