backbone.jstypescript

Converting Backbone structures to TypeScript


Looking at Backbonejs' implementation of the extend function, it shows that it isn't a basic prototype extension, and when backbone extensions are converted straight to TypeScript classes some things stop functioning. What is the right way to convert each component of Backbonejs (Model, Collection, Route, View, History) to a typescript class and make sure nothing is broken?

Thanks!

Update: The answer in this Q/A can also work for other backbone constructs.


Solution

  • This is because the code generated by TypeScript first calls the Router constructor and then declares the routes.

    Code generated by TypeScript compiler

    ...
    function AppRouter() {
        _super.apply(this, arguments);
    
        this.routes = { // <= routes defined after _super constructor
            "*actions": "defaultRoute"
        };
    }
    ...
    

    To fix this just call the Backbone Router function _bindRoutes() on your TypeScript object constructor.

    Example:

    class AppRouter extends Backbone.Router {
        routes = {
            "*actions": "defaultRoute"
        }
    
        constructor(){
            super();
            // call _bindRoutes() here function to bind your routes
            (<any>this)._bindRoutes();
        }
    
        defaultRoute() {
            document.write("Default Route Invoked");
        }
    }
    
    var app_router = new AppRouter();
    
    Backbone.history.start();
    

    Download a sample code here