【问题标题】:KnockoutObservableArray<T> not getting populatedKnockoutObservableArray<T> 没有被填充
【发布时间】:2014-06-18 10:04:30
【问题描述】:

鉴于以下代码,为什么 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;
}

【问题讨论】:

    标签: knockout.js typescript this knockout-mapping-plugin


    【解决方案1】:

    Knockout Binding Context。因为click 在原型上并且在没有任何明确的this 上下文的情况下被调用,所以调用它会丢失它属于哪个类实例。

    您还可以通过在 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);
        }
    }
    

    【讨论】:

    • @4imble:该解决方案实际上对我来说效果很好。我已经为 getJSON 中的回调找到了它,但我没有意识到我也需要为点击做这件事。谢谢!
    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2023-03-29
    • 2011-11-15
    相关资源
    最近更新 更多