KnockoutJS is having problems using custom Text parameters: according to ko.mapping.fromJS

I use ASP.NET MVC, Web API and KnockOutJS to create a site. Using the web API, I return a list of location objects, which are captured through a JQuery AJAX call and stored in an observable array.

$.getJSON(baseLocationUri, function (data) { $.each(data, function (key, val) { self.locations.push(ko.mapping.fromJS(val)); }); }); 

An example of the returned data might look like this (cropped for brevity): [{"LocationId": 1, "DisplayName": "Starbucks", "Address": "123 Main St." }]

This works fine, and I used the same code elsewhere.

I also have a multi-select list that is tied to an observable array. If I write this choice using "DisplayName" as an option to Text :, it works fine:

 <select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: 'DisplayName'"></select> 

Similarly, if I return DisplayName as a function, it still works:

 <select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName }"></select> 

BUT - if I try to add to another parameter - it fails. All I see in the user interface is "undefined".

 <select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName + ' | ' + item.Address }"></select> 

Just one more thing. If I remove the AJAX call and mapping and just create JavaScript objects with an observable location array in JavaScript, this last code works fine.

What am I missing?

+4
source share
1 answer

You tried:

  function (item) { return item.DisplayName() + ' | ' + item.Address() } 

Since ko.mapping.fromJS (val) converts DisplayName and Address to observables.

+5
source

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


All Articles