Created
June 21, 2014 07:09
-
-
Save BenEddy/b5c42f92178762226d35 to your computer and use it in GitHub Desktop.
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
class ContextMatters.CompositeRouter extends Backbone.Router | |
constructor: -> | |
@route("*path", "extractComponents") | |
super | |
extractComponents: (path) -> | |
@changes ||= {} | |
for namespace, payload of @_decode(path) | |
unless _.isEqual(@changes[namespace], payload) | |
@trigger("component_route:#{namespace}", payload) | |
@changes[namespace] = payload | |
navigate: (params, options = {}) -> | |
super @_encode(_.extend(@current(), params)), options | |
current: -> | |
@_decode(Backbone.history.getFragment()) | |
get: (namespace) -> | |
@current()[namespace] || {} | |
# Private | |
_encode: (json) -> | |
_.chain(json) | |
.map(@_encodeNamespace) | |
.flatten() | |
.value() | |
.join("/") | |
_encodeNamespace: (values, namespace) => | |
unless _.isString(values) | |
values = _.map(_.pairs(values), @_encodeValue).join("&") | |
[namespace, values.replace("/", "%2F", "g")] | |
_encodeValue: (pair) => | |
if _.isArray(pair[1]) | |
pair = [pair[0], @_encodeArray(pair[1])] | |
pair.join("=") | |
_encodeArray: (array) -> | |
"{" + _.map(array, encodeURI).join("|") + "}" | |
_decode: (string) -> | |
return {} unless _.str.include(string, "/") | |
_.object _.inGroupsOf(2, string.split("/"), @_destructure(@_decodeNamespace)) | |
_destructure: (receiver) -> | |
(array) -> receiver.apply(@, array) | |
_decodeNamespace: (namespace, tuple) => | |
tuple = tuple?.replace("%2F", "/", "g") | |
if _.str.include(tuple, "=") | |
[namespace, _.object(_.map(tuple.split("&"), @_decodeValue))] | |
else | |
[namespace, tuple] | |
_decodeValue: (tuple) => | |
[property, value] = tuple.split("=") | |
value = @_decodeArray(value) if @_isEncodedArray(value) | |
[property, value] | |
_isEncodedArray: (value) -> | |
value.indexOf("{") == 0 | |
_decodeArray: (value) -> | |
_.map(value.replace(/\{|\}/g, "").split("|"), decodeURI) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment