Trunk routing doesn't work when converted to TypeScript
I am 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 don't have compile time or runtime, but the code doesn't work. Why?
source to share
Add all initialized fields in the constructor and make the call 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();
source to share
I looked at Backbone.Router.extends
, and this is not a basic prototype extension, so you can't just switch from Backbone.Router.extends
extending the TypeScript class.
I would modify your TypeScript file to look more like your original JavaScript - you still get the benefit of intellisense and type validation - you just don't use the class:
var AppRouter = Backbone.Router.extend({
routes: {
"*actions": "defaultRoute"
},
defaultRoute: function () {
document.write("Default Route Invoked");
}
});
var app_router = new AppRouter();
Backbone.history.start();
source to share
As Steve Fenton mentioned this, because the Drawings extension doesn't work the same as the underscore / support extension method.
The main problem is that the router calls _bindRoutes () before the routes field has been set to a "subclass" in the hierachy script hierarchy.
Calling Backbone.Router.apply (this, arguments) in the constructor of your ts class, as described in orad, will ensure that this call is made after the routes .
Calling this function manually will do the trick as well.
and just FYI: call delegateEvents (this.events) in the constructor of your view classes if you want the dom events from your element to fire
source to share
The accepted answer doesn't work with typescript 3.x. The method super()
must be called before use this
. Reordering the code won't work because the trunk initializes the routes in the method super()
. Here is a version where the route config is directly passed to super()
.
class AppRouter extends Backbone.Router {
constructor() {
super({
routes: {
"*actions": "defaultRoute"
}
});
}
}
source to share