Created
January 17, 2018 23:28
-
-
Save dead-claudia/35903776ff0c8d7b7e7dc6bc8ca5d585 to your computer and use it in GitHub Desktop.
Attempt to implement the route resolver concept as a component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// API: | |
// `m(RouteResolver, {onmatch(path), render(Comp)}) -> Component` | |
// | |
// Note: this is all in pure ES5 | |
// | |
// Assumed extensions: | |
// - `m.route.default()` - Get the default route | |
var RouteResolver = { | |
oninit: function (vnode) { | |
"use strict" | |
function set(comp) { | |
vnode.state.comp = comp || "div" | |
} | |
function bail(e) { | |
m.route.set(m.route.default(), null, {replace: true}) | |
throw e | |
} | |
try { | |
var request = vnode.attrs.onmatch(m.route.get()) | |
if (request == null || typeof request.then !== "function") { | |
set(request) | |
} else { | |
Promise.resolve(request).then(set, bail).then(m.redraw) | |
} | |
} catch (e) { | |
bail(e) | |
} | |
}, | |
view: function (vnode) { | |
"use strict" | |
if (vnode.state.comp == null) return [] | |
return vnode.attrs.render(vnode.state.comp) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment