Skip to content

Commit

Permalink
match: allow additional values to be passed
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshuawuyts committed Dec 27, 2015
1 parent 60834e7 commit a984ec5
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 5 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ r1('/dada/child')
Initialize a router with a default route. Doesn't ignore querystrings and
hashes.

### router.on(route, cb(params))
### router.on(route, cb(params, [arg1, ...]))
Register a new route. The order in which routes are registered does not matter.
Routes can register multiple callbacks. The callback can return values when
called.

### val = router(route)
### val = router(route, [arg1, ...])
Match a route and execute the corresponding callback. Alias: `router.emit()`.
Returns a values from the matched route (e.g. useful for streams).
Returns a values from the matched route (e.g. useful for streams). Any
additional values will be passed to the matched route.

## Internals
Wayfarer is built on an internal trie structure. If you want to build a router
Expand Down
12 changes: 10 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const assert = require('assert')
const sliced = require('sliced')
const trie = require('./trie')

module.exports = Wayfarer
Expand Down Expand Up @@ -40,12 +41,19 @@ function Wayfarer (dft) {
// (str, obj?) -> null
function emit (route) {
assert.notEqual(route, undefined, "'route' must be defined")
const args = sliced(arguments)

const node = _trie.match(route)
if (node && node.cb) return node.cb(node.params)
if (node && node.cb) {
args[0] = node.params
return node.cb.apply(null, args)
}

const dft = _trie.match(_default)
if (dft && dft.cb) return dft.cb(dft.params)
if (dft && dft.cb) {
args[0] = dft.params
return dft.cb.apply(null, args)
}

throw new Error("route '" + route + "' did not match")
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
],
"license": "MIT",
"dependencies": {
"sliced": "^1.0.1",
"xtend": "^4.0.1"
},
"devDependencies": {
Expand Down
12 changes: 12 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ test('should match a default path', function (t) {
r('/nope')
})

test('should allow passing of extra values', function (t) {
t.plan(2)
const foo = {}
const bar = {}
const r = wayfarer()
r.on('/foo', function (params, arg1, arg2) {
t.equal(arg1, foo, 'arg1 was passed')
t.equal(arg2, bar, 'arg2 was passed')
})
r('/foo', foo, bar)
})

test('.on() should catch type errors', function (t) {
t.plan(2)
const r = wayfarer()
Expand Down

0 comments on commit a984ec5

Please sign in to comment.