Was it not the intention that TypeScript would handle the this scope for me?

↘锁芯ラ 提交于 2019-12-23 22:28:06

问题


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:


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


来源:https://stackoverflow.com/questions/16029630/was-it-not-the-intention-that-typescript-would-handle-the-this-scope-for-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!