Skip to content

Instantly share code, notes, and snippets.

@olivernn
Last active October 7, 2015 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivernn/3199627 to your computer and use it in GitHub Desktop.
Save olivernn/3199627 to your computer and use it in GitHub Desktop.
New Davis Hash Routing
Davis.hash = function () {
var handlers = [],
lastPolledLocation
var triggerHandlers = function (request) {
Davis.utils.forEach(handlers, function (handler) {
handler(request)
})
}
var current = function () {
return window.location.hash.replace(/^#?\/?/, '/')
}
var assign = function (req) {
req.fullPath = req.fullPath.split('#')[1]
if (req.method === 'get') {
window.location.hash = req.location()
} else {
triggerHandlers(req)
}
}
var onChange = function (handler) {
handlers.push(handler)
}
if ('onhashchange' in window) {
Davis.$(window).bind('hashchange', function () {
var request = new Davis.Request (current())
triggerHandlers(request)
})
} else {
setInterval(function () {
if (lastPolledLocation != current()) {
lastPolledLocation = current()
var request = new Davis.Request (lastPolledLocation)
triggerHandlers(request)
}
}, 200)
}
Davis.supported = function () {
return true
}
Davis.location.setLocationDelegate({
onChange: onChange,
current: current,
assign: assign,
replace: assign
})
}
Davis.extend(Davis.hash)
var app = Davis(function () {
this.get('/foo', function (req) {
// do something cool
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment