Last active
December 16, 2016 13:41
-
-
Save chrisdavies/b56d1011cd9ca9394d86 to your computer and use it in GitHub Desktop.
A naive wrapper around Backbone router to make it understand route specificity (so route order doesn't matter)...
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
// Example usage of SortedRouter | |
var SortedRouter = require('./sortedrouter'); | |
var router = new SortedRouter(); | |
// Supports multiple URLs | |
router.route('', 'books', show('<h1>Books</h1>')); | |
router.route('books/new', show('<h1>New Book</h1>')); | |
router.route('books/:id', show('<h1>Show Book</h1>')); | |
router.route('author', show('<h1>Author</h1>')); | |
// Initialize the router | |
router.init(); | |
// Just a helper function to show some HTML n stuff | |
function show(msg) { | |
return function () { | |
var argz = Array.prototype.slice.call(arguments).join(', '); | |
document.querySelector('main').innerHTML = msg + '<div>' + argz + '</div>'; | |
} | |
} |
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
'use strict'; | |
var Backbone = require('backbone'); | |
var _ = require('underscore'); | |
var SortedRouter = Backbone.Router.extend({ | |
sortedRoutes: {}, | |
// Overwrite the Backbone.Router.route method so we can | |
// register routes in the correct order. | |
route: function () { | |
var len = arguments.length - 1, | |
callback = arguments[arguments.length - 1]; | |
for (var i = 0; i < len; ++i) { | |
this.sortedRoutes[arguments[i]] = callback; | |
} | |
}, | |
init: function () { | |
// A magic number to force a route to be lowest specificity | |
// Number.MIN_VALUE didn't work... | |
var lowestRoute = -1000000; | |
var me = this; | |
// Register all routes, sorted by specificity | |
_.chain(_.pairs(this.sortedRoutes)) | |
.sortBy(function (route) { | |
var url = route[0]; | |
if (url.indexOf('*') >= 0) { | |
return lowestRoute; | |
} else { | |
return -url.split(':').length; | |
} | |
}) | |
.each(function (route) { | |
Backbone.Router.prototype.route.apply(me, route); | |
}); | |
// Start the backbone routing subsystem | |
Backbone.history.start(); | |
} | |
}); | |
module.exports = SortedRouter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment