문제

Given the following code, why would LookupEditorVM.lookups end up as 'undefined'?

I've verified that the data is coming back, but maybe I'm misunderstanding how ko.mapping works.

Code:

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;
}
도움이 되었습니까?

해결책

See Knockout Binding Context. Because click is on the prototype and is invoked without any explicit this context, invoking it loses which class instance it belonged to.

You can also fix this by using an arrow function in your ViewModel definition for any event handlers that will be invoked this way:

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);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top