Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Last active January 1, 2016 13:29
Show Gist options
  • Save rodneyrehm/8151261 to your computer and use it in GitHub Desktop.
Save rodneyrehm/8151261 to your computer and use it in GitHub Desktop.
URI.js fragment overloading for seamless `!/some/path` and `?some=data` handling
/*
* Extending URI.js for fragment abuse
*/
// --------------------------------------------------------------------------------
// EXAMPLE: storing a relative URL in the fragment ("FragmentURI")
// possibly helpful when working with backbone.js or sammy.js
// inspired by https://github.com/medialize/URI.js/pull/2
// --------------------------------------------------------------------------------
// Note: make sure this is the last file loaded!
// USAGE:
// var uri = URI("http://example.org/#!/foo/bar/baz.html");
// var furi = uri.fragment(true);
// furi.pathname() === '/foo/bar/baz.html';
// furi.pathname('/hello.html');
// uri.toString() === "http://example.org/#!/hello.html"
(function (root, factory) {
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (typeof exports === 'object') {
// Node
module.exports = factory(require('./URI'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['./URI'], factory);
} else {
// Browser globals (root is window)
factory(root.URI);
}
}(this, function (URI) {
"use strict";
var p = URI.prototype;
// old handlers we need to wrap
var f = p.fragment;
var b = p.build;
// add fragment(true) and fragment(URI) signatures
p.fragment = function(v, build) {
var fragment = this._parts.fragment || "";
var prefix = fragment.slice(0, 1);
var furi;
if (v === true) {
if (prefix === '!') {
// remove prefix for regular URIs
furi = new URI(fragment.slice(1) || "");
} else {
// keep the prefix as it's just a query string
furi = new URI(fragment);
}
this._fragmentURI = furi;
furi._parentURI = this;
return furi;
} else if (v instanceof URI) {
this._fragmentURI = v;
v._parentURI = this;
var s = v.build(false)._string;
if (s.slice(0, 1) === '?') {
// the prefix ? is already given by v.toString()
prefix = '';
} else {
// FIXME: ! is always added, this may be a problem
prefix = '!';
}
this._parts.fragment = prefix + s;
this.build(!build);
return this;
} else if (typeof v === "string") {
this._fragmentURI = undefined;
}
return f.call(this, v, build);
};
// make .build() of the actual URI aware of the FragmentURI
p.build = function(deferBuild) {
var t = b.call(this, deferBuild);
if (deferBuild !== false && this._parentURI) {
// update the parent
this._parentURI.fragment(this);
}
return t;
};
// extending existing object rather than defining something new
return {};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment