问题
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