Default Routes in a Backbone.js controller?

Martin Wawrusch picture Martin Wawrusch · May 22, 2011 · Viewed 23.3k times · Source

I want to set a default route for my backbone.js controller. Currently I do it like so:

class DealSearchController extends Backbone.Controller
    routes:
        'list' : 'showListView'
        'photos' : 'showPhotoView'
        'map' : 'showMapView'

    initialize: ->
        ....        
            window.location.hash = 'list' if ! _.include( _.keys(@routes),(window.location.hash || '').replace('#',''))

Is there a better way of doing it?

Answer

Bill Eisenhauer picture Bill Eisenhauer · May 23, 2011

Try adding this additional route as the last route in your controller:

'*path':  'defaultRoute'

and then handle it like this:

defaultRoute: function(path) {
    this.showListView();
}

This assumes the list route is your preferred default. This should work since Backbone.js will match the routes in order, but will always match the 'splat' route.