Merge pull request #40 from timwis/hash

router: add hash routing
This commit is contained in:
Yoshua Wuyts
2016-06-09 12:13:18 +02:00
3 changed files with 26 additions and 6 deletions
+4
View File
@@ -655,6 +655,10 @@ following values:
- __opts.href:__ default: `true`. Handle all relative `<a
href="<location>"></a>` clicks and update internal `state.location`
accordingly.
- __opts.hash:__ default: `false`. Enable a `subscription` to the hash change
event, updating the internal `state.location` state whenever the URL hash
changes (eg `localhost/#posts/123`). Enabling this option automatically
disables `opts.history` and `opts.href`.
## Errors
### Could not find DOM node (#id) to update
+19 -4
View File
@@ -2,6 +2,8 @@ const history = require('sheet-router/history')
const sheetRouter = require('sheet-router')
const document = require('global/document')
const href = require('sheet-router/href')
const hash = require('sheet-router/hash')
const hashMatch = require('hash-match')
const sendAction = require('send-action')
const mutate = require('xtend/mutable')
const assert = require('assert')
@@ -190,9 +192,13 @@ function choo () {
// initial application state model
// obj -> obj
function appInit (opts) {
const initialLocation = (opts.hash === true)
? hashMatch(document.location.hash)
: document.location.href
const model = {
namespace: 'app',
state: { location: document.location.href },
state: { location: initialLocation },
subscriptions: [],
reducers: {
// handle href links
@@ -204,10 +210,19 @@ function appInit (opts) {
}
}
// enable catching <href a=""></href> links
// enable HTML5 history API
if (opts.href !== false) pushLocationSub(href)
// if hash routing explicitly enabled, subscribe to it
if (opts.hash === true) {
pushLocationSub(function (navigate) {
hash(function (fragment) {
navigate(hashMatch(fragment))
})
})
// otherwise, subscribe to HTML5 history API
} else {
if (opts.history !== false) pushLocationSub(history)
// enable catching <a href=""></a> links
if (opts.href !== false) pushLocationSub(href)
}
return model
+2 -1
View File
@@ -20,8 +20,9 @@
"license": "MIT",
"dependencies": {
"global": "^4.3.0",
"hash-match": "^1.0.2",
"send-action": "^1.1.0",
"sheet-router": "^3.0.0",
"sheet-router": "^3.1.0",
"xhr": "^2.2.0",
"xtend": "^4.0.1",
"yo-yo": "^1.2.0"