Was it not the intention that TypeScript would han

2019-07-11 19:09发布

I am working with knockout and TypeScript .

I get an error on this:

AppViewModel.prototype.setActive = function (data, event) {
            this.active(data);
        };

from this TypeScript file:

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

Object # has no method 'active', it is bound like this:

<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 --> 

$Parent should be the AppViewModel. it works until I click the link.

I am not 100% sure if the error is related to something I do not understand with binding or its the typescript generated functions and this is not proper handled.

this in a prototype function refer to the object itself? or the function scope?

1条回答
Rolldiameter
2楼-- · 2019-07-11 20:09

TypeScript doesn't attempt to guess which this context you wanted. If you want setActive to always use the class instance as the this context, you can bind it in the constructor:

export class AppViewModel {
    ...
    constructor() {
        this.active = ko.observable();
        DataContext.getProjects(this.projects, this.error);
        this.setActive = this.setActive.bind(this);
    }
    ...
}
查看更多
登录 后发表回答