Pregunta

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;
}
¿Fue útil?

Solución

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);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top