是不是意图TypeScript会为我处理这个范围?

Pou*_*sen 2 knockout.js typescript

我正在使用knockout和TypeScript.

我收到一个错误:

AppViewModel.prototype.setActive = function (data, event) {
            this.active(data);
        };
Run Code Online (Sandbox Code Playgroud)

从这个TypeScript文件:

export class AppViewModel {

    ///Properties
    projects = projects;
    error = ko.observable();
    active = ko.observable();
    //setActive: (data,e)=>void;
    ///Constructor
    constructor()
    {
        this.active = ko.observable();
        DataContext.getProjects(this.projects, this.error);


    }

    isActive(data)
    {
        return this.active() == data;
    }
    setActive(data, event) {

        this.active(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

Object#没有方法'active',它绑定如下:

<li class="nav-header">Projects</li>
            <!-- ko foreach: projects -->
            <li class="">
                <a href="#" data-bind="click: $parent.setActive, css: { active: ($parent.isActive($data)) }">
                    <i class="icon-pencil"></i>
                    <span style="padding-right: 15px;" data-bind="text: title"></span>
                </a>
            </li>
            <!-- /ko --> 
Run Code Online (Sandbox Code Playgroud)

$ Parent应该是AppViewModel.它一直有效,直到我点击链接.

我不是100%确定错误是否与我不理解的绑定或其打字稿生成的函数有关,这是不正确的处理.

这在原型函数中指的是对象本身?还是功能范围?

Rya*_*ugh 5

TypeScript不会尝试猜测this您想要的上下文.如果要setActive始终使用类实例作为this上下文,可以bind在构造函数中使用它:

export class AppViewModel {
    ...
    constructor() {
        this.active = ko.observable();
        DataContext.getProjects(this.projects, this.error);
        this.setActive = this.setActive.bind(this);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)