I am retrieving Json data from a web api. The data is in the format:
[{"CustomerID":1,"CustomerName":"John"},{"CustomerID":2,"CustomerName":"Sally"}]
The real data is naturally more complex, but it has the format of an array of items that does not have a "name", e.g., {"customers":[...]}. I can't change the data being passed so this is what I have to live with.
I want to create a knockout model on this data with the mapping plugin and tie it to the view:
var vmCustomers = ko.mapping.fromJS(jsonObject);
ko.applyBindings(vmPartners);
My problem now is that I don't know how to access the data on the HTML-page. I can see that the data has been loaded into the model if I inspect vmCustomers and drill down in _latestValue.
What I want to be able to do in the HTML is the corresponding thing to
foreach: customers
I can get it working by building up the knockout-model manually and just use .mapping to fill it (or even fill it manually), but I would like to avoid that. What I am looking for is a way to get hold of the top array in the knockout model from the HTML code.
I am very new to knockout so there might be something fundamental that I am missing.
Don't fight against KO. Just create a proper viewmodel where you have a customers property to hold your data, this is the KO way of doing it. Anyway a viewmodel will be handy in the future when you will have a place to put additional logic/data.
var viewModel = { customers: ko.mapping.fromJS(jsonObject); }
ko.applyBindings(viewModel);
Then you can have have your data-bind="foreach: customers" in your view.
However if you don't want to have a viewmodel and you want to bind to an array you can't access it with a name like "customers" you need to reference it with the current context: with using the $data property:
data-bind="foreach: $data"
JS
var vmCustomers = ko.mapping.fromJS(jsonObject);
ko.applyBindings(vmCustomers);
Demo JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With