问题
Why does the option text get converted to a string of a function after the values has been updated from ko.mapping.fromJS?
Sample: 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);
Notice that after update has been pressed the option text becomes a function.
回答1:
The data that has been passed through the mapping plugin has now turned Name
and Id
into observables. So, when your function does '[' + item.Id + '] ' + item.Name
, you are concatenating strings with observables (which are functions).
If the Name
and Id
are always observables, then you would want to do:
'[' + item.Id() + '] ' + item.Name()
If you want to support either observables or non-observables, then you could do something like:
'[' + ko.utils.unwrapObservable(item.Id) + '] ' + ko.utils.unwrapObservable(item.Name)
ko.utils.unwrapObservable
will properly return the value for an observable or non-observable.
来源:https://stackoverflow.com/questions/9763211/option-text-becomes-a-function-string-after-updated-with-fromjs