Typescript类继承:覆盖ko.computed方法

Vik*_*iaR 5 knockout.js typescript

我有简单的课程:

/// <reference path="..\typings\jquery\jquery.d.ts"/>
/// <reference path="..\typings\knockout\knockout.d.ts"/>

module Some.Namespace {

    export class TestBase {
        public field1: KnockoutObservable<string> = ko.observable("");

        public onFieldChange: KnockoutComputed<string> = ko.computed(() => {
            return this.field1();
        }, this);
    }

    export class Test extends TestBase {
        public field2: KnockoutObservable<string> = ko.observable("");

        public onFieldChange() {
            super.onFieldChange() + this.field2();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题,打字稿不允许在重写方法中使用关键字super.它说:

错误1类'Some.Namespace.Test'不能扩展类'Some.Namespace.TestBase':类'Some.Namespace.Test'定义实例成员函数'onFieldChange',但扩展类'Some.Namespace.TestBase'将其定义为实例成员属性.

错误2只能通过'super'关键字访问基类的公共方法.

如何覆盖knockout计算方法并且不松开基本方法?

bas*_*rat 5

如果您自己定义相同的名称,则无法从TypeScript中的子类访问父实例成员属性.例如以下内容:

class TestBase {
    public field1;
    public onFieldChange = () => { // we need a way to reference this in the child
        return this.field1();
    };
}

class Test extends TestBase {

    parentOnFieldChange:any;
    constructor(){
        super(); // call super 

        // Implictly initialize local properties

        // copies local version not parent
        this.parentOnFieldChange = this.onFieldChange;
    }

    public field2;
    public onFieldChange = () => {
        this.parentOnFieldChange() + this.field2();
    }
}
Run Code Online (Sandbox Code Playgroud)

生成(细分):

 function Test() {
        var _this = this;
        _super.call(this); // call super

        // NO WAY to put code here 

        // Implictly initialize local properties
        this.onFieldChange = function () {
            _this.parentOnFieldChange() + _this.field2();
        };

        // OUR code on only added after

        // copies local version not parent
        this.parentOnFieldChange = this.onFieldChange;
    }
Run Code Online (Sandbox Code Playgroud)

解决方案使用实例成员函数

class TestBase {
    public field1;

    public onFieldChange() {
        return this.baseOnFieldChange();
    }

    private baseOnFieldChange = () => { // we need a way to reference this in the child
        return this.field1();
    };
}

class Test extends TestBase {

    parentOnFieldChange:any;
    constructor(){
        super(); // call super              
    }

    public field2;
    public onFieldChange(){
        return super.onFieldChange() + this.childOnFieldChange();
    }

    private childOnFieldChange = () => {
        return this.field2();
    }
}
Run Code Online (Sandbox Code Playgroud)