Commit 02fc697c authored by Ivan Tyagov's avatar Ivan Tyagov

Make use of adaptive router by Romain (WIP)

parent 30673f0b
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script data-main="require-renderjs_route.js"
type="text/javascript"
src="../../lib/require/require.js"></script>
<!-- <script>
/*global document, jQuery */
"use strict";
(function (document, $) {
$(document).ready(function () {});
}(document, jQuery));
</script>-->
</head>
<body>
<noscript>
Please enable Javascript
</noscript>
</body>
</html>
// JavaScript file that is used to load RenderJs depenencies
require.config({
baseUrl: "../..",
paths: {
route: "examples/route/route",
url: "examples/route/url",
jquery: "lib/jquery/jquery"
},
});
require([ "require-renderjs", "jquery", "route", "url" ], function(domReady) {
var body = $("body"),
initialize_route;
initialize_route = function () {
// Home route. Redirect to sub app /color/
body
.route("add", "", 1)
.done(function () {
// Default route. Redirect to color subapp
$.url.redirect('/color/');
});
// add gadget based application
body
.route("add", "/gadget", 1)
.done(function () {
// Default route. Redirect to color subapp
//$.url.redirect('/color/');
console.log("add gadget");
});
// /color app. Create subroutes and initialize DOM
body
.route("add", "/color<path:params>", 1)
.done(function () {
var i, j, k, increment = 150, page, container;
// Container for the selected color
page = "<p>Page generated at " + new Date() + "<\/p>";
page += "<a href='" + $.url.generateUrl("unknown") + "'>Wrong global route<a>";
page += "<ul style='list-style: none;'>";
for (i = 0; i < 256; i += increment) {
for (j = 0; j < 256; j += increment) {
for (k = 0; k < 256; k += increment) {
page += "<li><a style='text-decoration: none; display: block; width: 2em; " +
"background-color:rgb(" + i + "," + j + "," + k + ");' " +
"href='" + $.url.generateUrl("/color/" + i + "/" + j + "/" + k + "/") + "'" +
">&nbsp;<\/a><\/li>";
}
}
}
page += "<li style='text-align: center;'><a style='text-decoration: none; display: block; width: 2em;' href='" +
$.url.generateUrl("/color/X/X/X") + "'>XXX<a><\/li>";
page += "<\/ul>";
page += "<div style='display: block;'><\/div>";
$(this).html(page);
// Create sub routed in the container
container = $(this).find("div");
container
.route("add", "/color/", 2)
.done(function () {
$(this).text("Please select a color");
});
container
.route("add", "/color/<int:red>/<int:green>/<int:blue>/", 2)
.done(function (red, green, blue) {
$(this).html(
"<div style='background-color:rgb(" + red + "," + green + "," + blue + ");'>&nbsp;<\/div>" +
"<p>Color (" + red + "," + green + "," + blue + ") selected at " + new Date() + "<\/p>"
);
});
container
.route("go", $.url.getPath(), 2)
.fail(function () {
$(this).html("Unknown color (" + $.url.getPath() + ")");
});
});
};
initialize_route.apply(body, []);
// Trigger route change
$.url.onhashchange(function () {
body
.route("go", $.url.getPath())
.fail(function () {
// Method to display error to the user
$(this).html(
"<p>Oups, seems the route '<b>" + $.url.getPath() + "<\/b>' doesn't exist!<\/p>" +
"<a href='" + $.url.generateUrl("") + "'>Go back to home<\/a>"
);
// All routes have been deleted by fail.
// Recreate the default one.
initialize_route.apply(this, []);
});
});
});
/*global window, jQuery */
/*!
* route.js v1.0.0
*
* Copyright 2012, Romain Courteaud
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Mon Jul 16 2012
*/
"use strict";
(function (window, $) {
$.extend({
StatelessDeferred: function () {
var doneList = $.Callbacks("memory"),
promise = {
done: doneList.add,
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function (obj) {
var i,
keys = ['done', 'promise'];
if (obj === undefined) {
obj = promise;
} else {
for (i = 0; i < keys.length; i += 1) {
obj[keys[i]] = promise[keys[i]];
}
}
return obj;
}
},
deferred = promise.promise({});
deferred.resolveWith = doneList.fireWith;
// All done!
return deferred;
}
});
var routes = [],
current_priority = 0,
methods = {
add: function (pattern, priority) {
var i = 0,
inserted = false,
length = routes.length,
dfr = $.StatelessDeferred(),
context = $(this),
escapepattern,
matchingpattern;
if (priority === undefined) {
priority = 0;
}
if (pattern !== undefined) {
// http://simonwillison.net/2006/Jan/20/escape/
escapepattern = pattern.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
matchingpattern = escapepattern
.replace(/<int:\w+>/g, "(\\d+)")
.replace(/<path:\w+>/g, "(.+)")
.replace(/<\w+>/g, "([^/]+)");
while (!inserted) {
if ((i === length) || (priority >= routes[i][2])) {
routes.splice(i, 0, [new RegExp('^' + matchingpattern + '$'), dfr, priority, context]);
inserted = true;
} else {
i += 1;
}
}
}
return dfr.promise();
},
go: function (path, min_priority) {
var dfr = $.Deferred(),
context = $(this),
result;
if (min_priority === undefined) {
min_priority = 0;
}
setTimeout(function () {
var i = 0,
found = false,
slice_index = -1,
slice_priority = -1;
for (i = 0; i < routes.length; i += 1) {
if (slice_priority !== routes[i][2]) {
slice_priority = routes[i][2];
slice_index = i;
}
if (routes[i][2] < min_priority) {
break;
} else if (routes[i][0].test(path)) {
result = routes[i][0].exec(path);
dfr = routes[i][1];
context = routes[i][3];
current_priority = routes[i][2];
found = true;
break;
}
}
if (i === routes.length) {
slice_index = i;
}
if (slice_index > -1) {
routes = routes.slice(slice_index);
}
if (found) {
dfr.resolveWith(
context,
result.slice(1)
);
} else {
dfr.rejectWith(context);
}
});
return dfr.promise();
},
};
$.routereset = function () {
routes = [];
current_priority = 0;
};
$.routepriority = function () {
return current_priority;
};
$.fn.route = function (method) {
var result;
if (methods.hasOwnProperty(method)) {
result = methods[method].apply(
this,
Array.prototype.slice.call(arguments, 1)
);
} else {
$.error('Method ' + method +
' does not exist on jQuery.route');
}
return result;
};
}(window, jQuery));
/*!
* url.js v1.0.0
*
* Copyright 2012, Romain Courteaud
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Mon Jul 16 2012
*/
"use strict";
(function (window, $) {
var hashchangeinitialized = false,
previousurl,
currentcallback,
getRawHash = function () {
return window.location.toString().split('#')[1];
},
callbackwrapper = function () {
if (previousurl !== window.location.hash) {
previousurl = window.location.hash;
if (currentcallback !== undefined) {
currentcallback();
}
}
},
timeoutwrapper = function () {
callbackwrapper();
window.setTimeout(timeoutwrapper, 500);
};
function UrlHandler() {}
UrlHandler.prototype = {
'generateUrl': function (path, options) {
var pathhash,
hash = '#',
key;
if (path !== undefined) {
hash += encodeURIComponent(path);
}
hash = hash.replace(/%2F/g, '/');
pathhash = hash;
for (key in options) {
if (options.hasOwnProperty(key)) {
if (hash === pathhash) {
hash = hash + '?';
} else {
hash = hash + '&';
}
hash += encodeURIComponent(key) +
'=' + encodeURIComponent(options[key]);
}
}
return hash;
},
'go': function (path, options) {
window.location.hash = this.generateUrl(path, options);
},
'redirect': function (path, options) {
var host = window.location.protocol + '//' +
window.location.host +
window.location.pathname +
window.location.search;
window.location.replace(host + this.generateUrl(path, options));
// window.location.replace(window.location.href.replace(/#.*/, ""));
},
'getPath': function () {
var hash = getRawHash(),
result = '';
if (hash !== undefined) {
result = decodeURIComponent(hash.split('?')[0]);
}
return result;
},
'getOptions': function () {
var options = {},
hash = getRawHash(),
subhashes,
subhash,
index,
keyvalue;
if (hash !== undefined) {
hash = hash.split('?')[1];
if (hash !== undefined) {
subhashes = hash.split('&');
for (index in subhashes) {
if (subhashes.hasOwnProperty(index)) {
subhash = subhashes[index];
if (subhash !== '') {
keyvalue = subhash.split('=');
if (keyvalue.length === 2) {
options[decodeURIComponent(keyvalue[0])] =
decodeURIComponent(keyvalue[1]);
}
}
}
}
}
}
return options;
},
'onhashchange': function (callback) {
previousurl = undefined;
currentcallback = callback;
if (!hashchangeinitialized) {
if (window.onhashchange !== undefined) {
$(window).bind('hashchange', callbackwrapper);
window.setTimeout(callbackwrapper);
} else {
timeoutwrapper();
}
hashchangeinitialized = true;
}
},
};
// Expose to the global object
$.url = new UrlHandler();
}(window, jQuery));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment