Knockout.js 击出式耳环<;T>;没有人口

Knockout.js 击出式耳环<;T>;没有人口,knockout.js,typescript,this,knockout-mapping-plugin,Knockout.js,Typescript,This,Knockout Mapping Plugin,给定以下代码,为什么LookupEditorVM.lookups会以“未定义”结束 我已经验证了数据正在返回,但可能我误解了ko.mapping的工作原理 代码: class LookupEditorVM { lookups: KnockoutObservableArray<LookupVM>; click(item) { this.selected(item) } constructor(baseURL: string) {

给定以下代码,为什么LookupEditorVM.lookups会以“未定义”结束

我已经验证了数据正在返回,但可能我误解了ko.mapping的工作原理

代码:

class LookupEditorVM {
    lookups: KnockoutObservableArray<LookupVM>;

    click(item) {
        this.selected(item)
    }

    constructor(baseURL: string) {
        this.lookups = ko.observableArray<LookupVM>([]);
        $.getJSON(baseURL, (data) => {
            ko.mapping.fromJS(data, {}, this.lookups);
        });

        this.selected = ko.observable(undefined);

    }
}

class LookupVM {
    ID: number;
    Name: string;
    DisplayName: string;
    Description: string;
}
类LookupEditorVM{
查找:淘汰赛;
单击(项目){
此。已选定(项目)
}
构造函数(baseURL:string){
this.lookups=ko.observearray([]);
$.getJSON(baseURL,(数据)=>{
fromJS(数据,{},this.lookups);
});
此项选择=可观察(未定义);
}
}
类查找VM{
ID:编号;
名称:字符串;
显示名称:字符串;
描述:字符串;
}
请参阅。因为
click
位于原型上,并且在没有任何显式
上下文的情况下被调用,所以调用它会丢失它所属的类实例

您还可以通过在ViewModel定义中使用箭头函数修复此问题,该函数用于任何将以这种方式调用的事件处理程序:

class LookupEditorVM {
    lookups: KnockoutObservableArray<LookupVM>;
    selected: KnockoutObservable<LookupVM>;

    click = (item) => { // <--- Arrow function preserves 'this'
        this.selected(item)
    }

    constructor(baseURL: string) {
        this.lookups = ko.observableArray<LookupVM>([]);
        $.getJSON(baseURL, (data) => {
            ko.mapping.fromJS(data, {}, this.lookups);
        });

        this.selected = ko.observable(undefined);
    }
}
类LookupEditorVM{
查找:淘汰赛;
选择:敲除可观察;
单击=(项目)=>{//{
fromJS(数据,{},this.lookups);
});
此项选择=可观察(未定义);
}
}

@4imble:这个解决方案实际上对我很有效。我已经为getJSON中的回调找到了答案,但我没有意识到我也需要为单击找到答案。谢谢