Last active
October 3, 2016 22:59
-
-
Save dead-claudia/2e1a78f24f1979f2b7eb to your computer and use it in GitHub Desktop.
Conditional routing for Mithril
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
;(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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you explain how to use this? Tks