Option text becomes function string after upgrade using JS function

Why is the option text converted to a function string after the values ​​have been updated from ko.mapping.fromJS?

Example: http://jsfiddle.net/tYnc6/24/

Html:

<div> <select data-bind="options: items, value: selected, optionsText: function(item) { return ('[' + item.Id + '] ' + item.Name) }, optionsCaption: 'Choose...'"></select> <button data-bind="click: update">Update</button> </div> 

Javascript:

 var mapping = { key: function(data) { return ko.utils.unwrapObservable(data.Id); } }; viewModel = { items: ko.observableArray([ {Name: 'foo', Id: '1'}, {Name: 'bar', Id: '2'} ]), selected: ko.observable(), update: function() { data = [ {Name: 'foo', Id: '1'}, {Name: 'bar', Id: '2'}, {Name: 'baz', Id: '3'} ]; ko.mapping.fromJS(data, mapping, this.items); } } ko.applyBindings(viewModel); 

Please note that after the update has been clicked, the option text becomes a function.

+2
source share
1 answer

The data passed through the display plugin has now turned Name and Id into observables. So, when your function executes '[' + item.Id + '] ' + item.Name , you combine the lines with the observables (which are functions).

If Name and Id are always observable, then you would like to do:

'[' + item.Id() + '] ' + item.Name()

If you want to support either observable or not observable, then you can do something like:

'[' + ko.utils.unwrapObservable(item.Id) + '] ' + ko.utils.unwrapObservable(item.Name)

ko.utils.unwrapObservable will correctly return a value for observable or not observable.

+3
source

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


All Articles