将一个选择选项绑定到一个对象

KnockoutJS - Binding a select option to an object

本文关键字:选项 绑定 一个对象 选择 一个      更新时间:2023-09-26

同上…

这是我的属性视图模型

function propertyViewModel() {
    var self = this;
    self.propertyTypeList = ko.observableArray([]);
    self.selectedPropertyType = ko.observable();
}

这是我的模型属性类型:

function propertyTypeModel(id, name) {
    this.Id = ko.observable(id);
    this.Name = ko.observable(name);
}

我使用signalR从数据库获取数据,并在成功时调用以下客户端函数:

connection.client.populatePropertyTypeList = function (propertyTypeList) {
    var mappedTypes = $.map(propertyTypeList, function (item) {
        return new propertyTypeModel(item.Id, item.Name);
    });
    self.propertyTypeList(mappedTypes);
};

:

connection.client.populatePropertyDetails = function (property) {
    self.selectedPropertyType(new propertyTypeModel(property.PropertyType.Id, property.PropertyType.Name));
};

第一个用所有可能的属性类型填充可观察数组,第二个获取相关的属性类型并将其绑定到selectedPropertyType。

一切都如预期的那样工作,直到我尝试引入一个下拉列表,并使用selectedPropertyType的名称预填充它,如下所示:

<select data-bind="options: propertyTypeList, optionsText: 'Name', value: selectedPropertyType"></select>

这使得我的可观察对象(selectedPropertyType)将其值更改为列表中的第一个可用选项。我的理解是,虽然此列表呈现propertyTypeList尚未填充,并导致selectedPropertyType默认为第一个可用值,但为什么Knockout在调用connection.client.populatePropertyDetails时不更新对象?

如果我引入一个只持有Id的新对象,我可以将选择列表绑定到Id,但是我想将它绑定到整个selectedPropertyType对象。这可能吗?

您在populatePropertyDetails回调中创建了一个新对象。

尽管this.Idthis.NamepropertyTypeList中对应的对象具有相同的属性值,但不是相同的对象

试着把你的回调改成这样:

connection.client.populatePropertyDetails = function (property) {
    var type = property.PropertyType,
        list = self.propertyTypeList();
    var foundType = ko.utils.arrayFirst(list, function(item) {
        return item.Id() == type.Id && item.Name() == type.Name;
    });
    if(foundType) {
        self.selectedPropertyType(foundType);
    }
};