KnockoutJS - binding a selection option to an object

Like this post ...

This is my property view model:

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

This is my model for a property type:

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

I retrieve data from the database using signal R and call the following client-side functions:

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

and

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

The first one fills the observed array with all possible types of properties, and the second receives the corresponding property type and binds it to the selected typePropertyType.

Everything works as expected until I try to present a drop-down list and pre-populate it with the selectedPropertyType name as follows:

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

This makes my observed object (selectedPropertyType) change its value to the first available parameter in the list. My understanding is that while this list is rendered, the TypeList property is not yet populated and calls the selectedPropertyType value by default for the first available value, but then why does Knockout not update the object when calling connection.client.populatePropertyDetails?

I can bind a select list to an identifier if I introduce a new object containing only Id, however I would like to associate it with the whole selectedPropertyType object. Is it possible?

+4
source share
1 answer

You create a new object in your populatePropertyDetails .

Even if it has the same property values ​​for this.Id and this.Name as the corresponding object in propertyTypeList , it is not the same object .

Try changing your answer to this:

 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); } }; 
+6
source

Source: https://habr.com/ru/post/1481338/


All Articles