Trying to map array from JSON to knockout using mappings

故事扮演 提交于 2019-12-14 03:10:46

问题


Hi I have a JSON array like so

[{
    "id": "537901a53513fa3374bec718",
    "images": [],
    "itemImage": "img/3.jpg",
    "createdDate": "5/18/2014 6:53:25 PM",
    "location": [
        -2.057802,
        52.609711
    ]
},
{
    "id": "537901a53513fa3374bec710",
    "images": [
        "img/17.jpg"
    ],
    "itemImage": "img/1.jpg",
    "createdDate": "5/18/2014 6:53:25 PM",
    "location": [
        -2.062251,
        52.612397
    ]
}]

I'm trying to use the ko.mapping.fromJSON / JS, but i keep messing up sigh :(

  var viewModel = {};

in my Ajax success function,

  viewModel.model = ko.mapping.fromJSON(data);
  ko.applyBindings(viewModel);

HTML

   <div data-bind=" foreach: model">
       <div data-bind="text: body"></div>
   </div>            

I've tried following this post answered by John Papa, but I think my array is different. Knockout JS mapping plugin confusion I can do it manually, but am bored of manually building view models :).

Also tried this and got confused further Can't map JSON object to ViewModel (knockout js)

Would any kind souls be able to point me in the right direction ?


回答1:


All you need to do is the following:

var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

You loop them as follows:

<table class="table table-striped">
        <tbody data-bind="foreach: $data">
            <tr>

                <td data-bind="text: id"></td>
            </tr>
        </tbody>
    </table>

See example here:

http://jsfiddle.net/wr5W7/5/



来源:https://stackoverflow.com/questions/24295450/trying-to-map-array-from-json-to-knockout-using-mappings

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