A little URL generator for Backbone.js

Just something I wrote at work today: our app has a model that acts as an API for submodules, and as part of it, it allows interlinking between different modules (aka ‘screens’).

You can pass this method the ‘slug’ of any screen (module) in the app, plus any number of arguments and it builds a URL for them. Each of the args is separated by a ‘/‘.

Arrays are joined with commas, functions are executed, objects are strigified via jQuery’s $.param, and strings/numbers are just given as-is.

// Build URL for any screen:
urlify: function(slug) {
	slug = slug || "";

	// Create array of strings from arguments:
	var args = _.map(Array.prototype.slice.call(arguments, 1), function(arg) {
		// Join arrays, evaluate functions, stringify objects, leave strings/numbers:
		return _.isArray(arg) ? arg.join(',') : _.isFunction(arg) ? arg() : _.isObject(arg) ? $.param(arg) : arg;
	});
	return (!Backbone.history.options.pushState ? '#' : '') + slug + '/' + ( args.length > 0 ? args.join('/') + '/' : '' );
}

// for example:
Model.urlify('screen-name', 1253431, ["a","b","c"], {a:1});
// => "#screen-name/1253431/a,b,c/a%5Bb%5D=1/"

What the hash?

Note the (!Backbone.history.options.pushState ? '#' : '') ?

When supporting pushState in Backbone.history, some browsers will use e.g. app.com/#page, while others will use simply app.com/page.

But what about when you need to template in links to other sections of your app, but you’re not sure if the user’s browser supports pushState?

I got your back, bro. What this function does is inserts a hash # when pushState is not supported, so that inter-linking modules still get routed to the correct place.

Not sure if any of this makes sense, as currently a little tipsy – will update tomorrow with better info and examples.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>