Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Last active October 3, 2016 22:59
Show Gist options
  • Save dead-claudia/2e1a78f24f1979f2b7eb to your computer and use it in GitHub Desktop.
Save dead-claudia/2e1a78f24f1979f2b7eb to your computer and use it in GitHub Desktop.
Conditional routing for Mithril
;(function (mod) {
if (typeof module === "object" && module != null && module.exports) {
// Node
module.exports = mod
} else if (typeof define === "function" && define.amd) {
// AMD
define("mithril-configure", function () { return mod })
} else if (typeof exports === "object" && exports != null) {
// Other CommonJS
exports.init = mod
} else {
// Browser - just initialize it immediately (common use case)
mod(m)
}
})(function (m) {
if (typeof m !== "function" || typeof m.route !== "function") {
throw new TypeError("Expected a Mithril instance")
}
if (!m.route.configure) m.route.configure = function (condition, run) {
var old = m.route
var check = m.route = function (route) {
if ({}.toString.call(route) !== "[object String]" || !condition(route)) {
return old.apply(this, arguments)
} else {
return run(old, route)
}
}
// So the properties are still accessible (and doesn't break Mithril)
for (var i in old) if ({}.hasOwnProperty.call(old, i)) {
check[i] = old[i]
}
// So it's easy to restore
return function () {
if (m.route !== check) {
throw new ReferenceError("m.route no longer references this checker!")
}
m.route = old
}
}
return m
});
@volnei
Copy link

volnei commented Oct 3, 2016

Can you explain how to use this? Tks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment