Option text becomes a function string after updated with fromJS
Asked Answered
C

1

2

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.

Crewelwork answered 18/3, 2012 at 23:18 Comment(0)
M
3

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.

Maxia answered 18/3, 2012 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.