TypeScript是否会为我处理此范围? [英] Was it not the intention that TypeScript would handle the this scope for me?

查看:86
本文介绍了TypeScript是否会为我处理此范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用敲除和TypeScript.

I am working with knockout and TypeScript .

我在此出现错误:

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

来自此TypeScript文件:

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

对象#没有方法'active',它的绑定方式是这样的:

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应该是AppViewModel.在点击链接之前,它一直有效.

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

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

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?

推荐答案

TypeScript不会尝试猜测您想要哪个this上下文.如果希望setActive始终将类实例用作this上下文,则可以在构造函数中bind对其进行使用:

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

这篇关于TypeScript是否会为我处理此范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆