Commit 2bb1d0e5 authored by Thomas Lechauve's avatar Thomas Lechauve

New: Searching a route and call its callback

parent 147aa91b
......@@ -5,12 +5,12 @@
routes: {
list: [],
current: null,
add: function (route, level, callback, context) {
var r, keys, i;
if (typeof this.list[level] === 'undefined') {
this.list[level] = [];
}
route = route.replace(/:\w+/g, '([^\/]+)');
r = {
'route': route,
'level': level,
......@@ -27,28 +27,35 @@
i = this.list[level].length;
this.list[level][i] = r;
},
clean: function (level) {
this.list = this.list.slice(0, level);
},
cleanAll: function () {
this.list = this.list.slice(0, 0);
},
search: function (hash) {
var stop = false,
i = 0,
j = 0,
i = 0, j = 0,
regex,
result;
console.log(hash)
result,
extracted;
while ((stop === false) && (i < this.list.length)) {
j = 0;
while ((stop === false) && (j < this.list[i].length)) {
regex = new RegExp('^' + this.list[i][j].route + '$');
extracted = $.router.extractKeys(this.list[i][j].route);
regex = new RegExp('^' + extracted.regex + '$');
if (regex.test(hash.route)) {
result = regex.exec(hash.route);
stop = true;
console.log(result)
result.shift();
//delete hash.route;
for (var k = 0; k < result.length; k += 1) {
hash[extracted.keys[k]] = result[k];
}
this.current = this.list[i][j];
this.clean(i + 1);
this.list[i][j].callback(hash);
}
j += 1;
......@@ -58,6 +65,18 @@
}
},
extractKeys: function (regex) {
var re_key = new RegExp(/:(\w+)/),
keys = [],
result;
while (re_key.test(regex)) {
result = re_key.exec(regex);
keys.push(result[1]);
regex = regex.replace(result[0], '([^\/]+)');
}
return {'regex': regex, 'keys': keys}
},
deserialize: function (params) {
var result = {},
p,
......
......@@ -45,21 +45,25 @@ $(function () {
test('search test', function () {
var url1 = {'route': '#/new/path', 'param1': 'foo1', 'param2': 'foo2', 'filter': true},
url2 = {'route': '#/new/path/1', 'param1': 'foo1'},
spy1 = sinon.spy(),
spy2 = sinon.spy();
console.log(url1);
$.router.routes.add(url1.route, 0, spy1);
$.router.routes.add('#/new/path/:id', 1, spy2);
url3 = {'route': '#/new/path/1/foo', 'param1': 'foo1'},
spy = sinon.spy();
$.router.routes.add('#/new/path', 0, spy);
$.router.routes.add('#/new/path/:id', 1, spy);
$.router.routes.add('#/new/path/:id/:other', 2, spy);
$.router.routes.search(url1);
//delete url1.route;
//ok(spy1.calledOnce);
//ok(spy1.calledWith(url1));
delete url1.route;
ok(spy.calledWith(url1));
//$.router.routes.search(url2);
//delete url2.route;
//ok(spy2.calledOnce);
//ok(spy2.calledWith(url2));
$.router.routes.search(url2);
delete url2.route;
ok(spy.calledWith(url2));
$.router.routes.search(url3);
delete url3.route;
ok(spy.calledWith(url3));
ok(spy.calledThrice);
});
module('router methods tests', {
......
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