KnockoutJS - 将select选项绑定到对象

Jer*_*rry 4 javascript knockout.js

此帖相似......

这是我的属性视图模型:

function propertyViewModel() {
    var self = this;
    self.propertyTypeList = ko.observableArray([]);
    self.selectedPropertyType = ko.observable();
}
Run Code Online (Sandbox Code Playgroud)

这是我的属性类型模型:

function propertyTypeModel(id, name) {
    this.Id = ko.observable(id);
    this.Name = ko.observable(name);
}
Run Code Online (Sandbox Code Playgroud)

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

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

和:

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

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

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

<select data-bind="options: propertyTypeList, optionsText: 'Name', value: selectedPropertyType"></select>
Run Code Online (Sandbox Code Playgroud)

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

如果我引入一个仅包含Id的新对象,我可以将选择列表绑定到Id,但是我希望将它绑定到整个selectedPropertyType对象.可能吗?

Set*_*thi 6

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

即使它具有相同的属性值this.Idthis.Name相应的对象propertyTypeList,它也不是同一个对象.

尝试将回调更改为:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 我接受了Jalayn的编辑,因为虽然代码基本上是相同的,但是在`ko.utils`中使用`arrayFirst`比使用`return'的`for`循环更能描述实现的内容. `或`break;`声明.因此,对未来的开发人员/调试人员来说更好. (2认同)