Search code examples
javascriptjqueryhtmlbackbone.jsurl-routing

Setting up Backbone router


Can't figure out what's going wrong with my Backbone router. Can anyone spot a mistake in the following block of code? The index route is working fine but the classes route isn't ever triggering (e.g. when I navigate to a URL like localhost/classes/test)

var app = app || {};

$(function() {


    app.Router = Backbone.Router.extend({
        routes: {
            '' : 'index',
            'classes/:id' : 'classes'
        },

        initialize: function() {
            this.classList = new app.ClassCollection();
        },

        index: function() {
            this.menuView = new app.ClassCollectionView({collection: this.classList});
        },

        classes: function(id) {
            console.log("hello")
            var _class = new app.ClassModel({id: id});
            this.classView = new app.ClassPageView({model: _class});
        }
    });

    router = new app.Router();
    Backbone.history.start({pushState: true});
})

If everything looks in order, there's probably a bug somewhere else in my code.


Solution

  • Backbone.router is extending hashbang navigation. so localhost/#classes/test

    should lead to your method. ALSO! pay attention that emty route should be at the end of the routes list. It's like else if construction, if route matches "" (default # ?!) it will never match other routes