TypeScript是否会为我处理此范围? [英] Was it not the intention that TypeScript would handle the this scope for me?
问题描述
我正在使用敲除和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屋!