Skip to content

Commit

Permalink
Merge pull request #39 from abradley2/ordered-routes
Browse files Browse the repository at this point in the history
Add routes in order of depth in 'on' method
  • Loading branch information
Krasimir Tsonev authored Sep 13, 2016
2 parents 0323016 + 21522b1 commit de50192
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 23 deletions.
52 changes: 34 additions & 18 deletions lib/navigo.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/navigo.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/navigo.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/navigo.min.js.map

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ function replaceDynamicURLParts(route) {
return { regexp, paramNames };
}

function getUrlDepth(url) {
return url.replace(/\/$/, '').split('/').length;
}

function compareUrlDepth(urlA, urlB) {
return getUrlDepth(urlA) < getUrlDepth(urlB);
}

function findMatchedRoutes(url, routes = []) {
return routes
.map(route => {
Expand Down Expand Up @@ -122,9 +130,11 @@ Navigo.prototype = {
if (args.length >= 2) {
this._add(args[0], args[1]);
} else if (typeof args[0] === 'object') {
for (let route in args[0]) {
let orderedRoutes = Object.keys(args[0]).sort(compareUrlDepth);

orderedRoutes.forEach(route => {
this._add(route, args[0][route]);
}
});
} else if (typeof args[0] === 'function') {
this._defaultHandler = args[0];
}
Expand Down
14 changes: 14 additions & 0 deletions test/Navigo.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,20 @@ describe('Given an instance of Navigo', function () {
.to.be.calledOnce
.and.to.be.calledWith({ tripId: '42' });
});
it('should set the routes in order of depth', function () {
var handler = sinon.spy();

router = new Navigo('http://site.com/', true);
router.on({
'products': { as: 'products', uses: handler },
'products/:productId': { as: 'products.id', uses: handler}
});
router.resolve('products/42');

expect(handler)
.to.be.calledOnce
.and.to.be.calledWith({ productId: '42' })
});
});
});

Expand Down

0 comments on commit de50192

Please sign in to comment.