3

查看 Backbonejs 的extend 函数实现,它表明它不是一个基本的原型扩展,并且当主干扩展直接转换为 TypeScript 类时,有些东西会停止运行。将 Backbonejs 的每个组件(模型、集合、路由、视图、历史)转换为 typescript 类并确保没有损坏的正确方法是什么?

谢谢!

更新:此 Q/A中 的答案也适用于其他骨干结构。

4

1 回答 1

1

这是因为 TypeScript 生成的代码首先调用了 Router 构造函数,然后声明了路由。

TypeScript 编译器生成的代码

...
function AppRouter() {
    _super.apply(this, arguments);

    this.routes = { // <= routes defined after _super constructor
        "*actions": "defaultRoute"
    };
}
...

_bindRoutes()要解决这个问题,只需在 TypeScript 对象构造函数上调用 Backbone Router 函数。

例子:

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();

在此处下载示例代码

于 2013-02-02T02:23:26.187 回答