简体   繁体   中英

Knockout maping.fromJS for observableArray from json object. Data gets lost

I have a view model with an observable and an observableArray. A button click is suppose to populate a JSON object and map it to the view model...which I believe "should" populate the observableArray. The button click happens. No errors. If I run through the debugger when the mapping occurs the obserable object gets populated but the obserableArray does not. Which means that the HTML objects that are suppose to display based on the observableArray do not get updated.

HTML:

<div data-bind="if: ErrorMessages().length"> <span>Error Messages</span>
    <ul data-bind="foreach: ErrorMessages">
        <li> <span data-bind="text: Description"></span>
        </li>
    </ul>
</div>
<button data-bind="click: ShowErrors">Go</button>

var ViewModel = function () {
    var me = this;
    me.AData = ko.observable();
    me.ErrorMessages = ko.observableArray([]);

Javascript:

    me.ShowErrors = function () {


        var testdata = {
            AData: {
                Something: 1
            },
            ErrorMessages: [{
                Description: 'Error #1',
                Code: '01'
            }, {
                Description: 'Error #2',
                Code: '02'
            }]
        };
        var jsonData = ko.toJSON(testdata);

        ko.mapping.fromJS(jsonData, {}, me);
    };
};
ko.applyBindings(new ViewModel());

http://jsfiddle.net/Eves/v9SEk/4/

My real code reaches out and gets data from a web service. I figure the above creating an object and converting it to JSON and then mapping it using ko.mapping.fromJS best represents what is happening. Anyways...

I suspect I've done something stupid, or at least, assumed something I should not have.

You are converting to JSON with ko.toJSON(testdata) but you are not reading from JSON with the ko.mapping.fromJS(jsonData, {}, me); but from a plain JS object.

The toJSON and fromJSON method should be used in pairs:

var jsonData = ko.toJSON(testdata);

ko.mapping.fromJSON(jsonData, {}, me);

and the same applies to the toJS and fromJS :

var jsonData = ko.toJS(testdata);

ko.mapping.fromJS(jsonData, {}, me);

Demo JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM