简体   繁体   中英

Knockoutjs Mapping - Trouble getting it to work

I have trouble understanding how mapping works with knockoutjs.

Pretext:

I have an API, that returns JSON

I want to map that JSON to a list in my view

javascript:

    var data = JSON.stringify([
        {
            "text": "this be some text"
        },
        {
            "text": "some more text here"
        }
    ]);

    var viewModel = ko.mapping.fromJSON(data);

    var updateData = function(){
        var newData = JSON.stringify([
            {
                "text": "this be some asdfasdfasdf"
            },
            {
                "text": "some more asdfasdfdfdf here"
            }
        ]);

        ko.mapping.fromJSON(newData, viewModel);
    }

    ko.applyBindings(viewModel);

data and newData are in the same format I would be getting my data from API calls. (Just array of objects)

How can i output that data?

<ul data-bind="foreach: whatgoeshere?">
    <li data-bind="text: text"></li>
</ul>

Thanks for explaining to me how this magic works ;) Have a good day

At first you should use fromJS instead of fromJSON as the last one expects a string that contains a json.

Another thing is that you should modify your viewmodel like this:

{ arr: [ { name:'text' }, ... ] }

And type arr in your foreach binding.

If you don't want to modify your model then you may pass $root to your foreach that points to your model used in ko.applyBindings

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