knockout.js - Knockout 可观察属性包含函数代码

标签 knockout.js typescript

首先,我使用的是 Knockout 和 TypeScript。

给定以下源代码:

class LookupEditorVM {
    lookups: KnockoutObservableArray<LookupVM>;
    selected: KnockoutObservable<LookupVM>;
    baseURL: string = "/Admin/Lookup/";

    constructor() {
        this.lookups = ko.observableArray<LookupVM>([]);
        this.selected = ko.observable<LookupVM>();

        $.getJSON(this.baseURL + "ListLookups", (data) => {
            ko.mapping.fromJS(data, {}, this.lookups);
        });

        this.selected.subscribe(() => {
            this.getListItems();
        });
    }

    getListItems() {
        $.getJSON(this.baseURL + "GetLookupItems/" + this.selected().ID, (data) => {
            ko.mapping.fromJS(data, {}, this.selected().LookupItems);
        });
    }
}

class LookupVM {
    ID: number;
    Name: string;
    DisplayName: string;
    Description: string;
    LookupItems: KnockoutObservableArray<LookupItemVM>;

    constructor(ID?: number, Name?: string, DisplayName?: string, Description?: string) {
        this.ID = ID;
        this.Name = Name;
        this.DisplayName = DisplayName;
        this.Description = Description;
        this.LookupItems = ko.observableArray([]);
    }
}

下面的函数让我很不舒服:

getListItems() {
    $.getJSON(this.baseURL + "GetLookupItems/" + this.selected().ID, (data) => {
        ko.mapping.fromJS(data, {}, this.selected().LookupItems);
    });
}

selected 的 ID 属性与一些 knockout 函数的文本一起出现。它应该是一个数字。我也尝试过将 ID 作为数字类型传递给 getListItems,但它仍然作为函数文本传递。

我错过了什么?

更新

我已将 this.selected().ID 更改为 this.selected().ID() 以考虑可观察对象。我还采纳了 Mark 的建议并将 LookupVM 属性更改为可观察的。

最佳答案

默认情况下,Knockout Mapping 插件会将其创建的对象中的所有属性创建为可观察对象(这是您看到的值的“函数”)。所以,这一行:

ko.mapping.fromJS(data, {}, this.lookups);

创建一个 LookupVM 数组,其中每个属性都是可观察的。类定义中指定的 TypeScript 类型将被忽略,因为它们在运行时不存在。

这可能是您想要的 - 在这种情况下,只需将您的属性更改为可观察的,例如

class LookupVM {
    ID: KnockoutObservable<number>;
    Name: KnockoutObservable<string>;
    etc.

并在您的其他 ajax 调用中使用 this.selected().ID()

或者,您可以告诉 Mapping 插件复制属性而不是创建可观察对象:

ko.mapping.fromJS(data, {"copy":["ID","Name","DisplayName","Description"]}, this.lookups);

在这种情况下,我不确定您希望如何处理 LookupItems 属性 - 您可能需要检查 documentation .

关于knockout.js - Knockout 可观察属性包含函数代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529284/

相关文章:

javascript - knockout 名单不会添加新项目

jquery - TypeScript:在事件中使用 jquery $(this)

reactjs - TS 表达式产生的联合类型太复杂,无法用 Material-UI 和 @react-three/fiber 表示

javascript - Typescript:检查变量的真实性不会对未定义进行类型防护吗?

javascript - Angular/Typescript promise

所有子控件的 Angular 形式 updateValueAndValidity

javascript - 将某些 observableArray 对象属性转换为 observable

javascript - 模型在命名空间外不可访问

javascript - Knockout.js:如何使用 foreach 数据绑定(bind)动态分配 id?

css - 未应用样式