Search code examples
backbone.jstypescriptbackbone-routing

Backbone routing doesn't work when converted to TypeScript


I'm trying to convert a basic Backbone.js router declaration to TypeScript.

var AppRouter = Backbone.Router.extend({
    routes: {
        "*actions": "defaultRoute"
    },

    defaultRoute: function () {
        document.write("Default Route Invoked");
    }
});

var app_router = new AppRouter();

Backbone.history.start();

My converted code is the following which doesn't work:

class AppRouter extends Backbone.Router {
    routes = {
        "*actions": "defaultRoute"
    }

    defaultRoute() {
        document.write("Default Route Invoked");
    }
}

var app_router = new AppRouter();

Backbone.history.start();

I get no compile time or runtime errors but the code does not function. Why?


Solution

  • Add all initialized fields in the constructor and make a call to super at the end:

    class AppRouter extends Backbone.Router {
    
        routes: any;
        constructor(options?: Backbone.RouterOptions) {
    
            this.routes = {
                "*actions": "defaultRoute"
            }
    
            super(options);
        }
    
        initialize() {
            // can put more init code here to run after constructor
        }
    
        defaultRoute() {
            document.write("Default Route Invoked");
        }
    }
    
    var app_router = new AppRouter();
    
    Backbone.history.start();