Option text becomes a function string after updated with fromJS

假如想象 提交于 2019-12-11 03:02:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!