Search code examples
controllerbackbone.js

Default Routes in a Backbone.js controller?


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?


Solution

  • 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.