One example, of reading JSON, and displaying content of JSON as check boxes.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/lib/knockout-3.5.1.js"></script>
<script type="text/javascript" src="js/lib/jquery-3.4.1.min.js"></script>
</head>
<body onload="DoApply()">
Cities:
<span data-bind="template: {name: 'cities-template', foreach: cities}"></span>
<script type="text/html" id="cities-template" >
<br/>
<input data-bind="id: id, name: name" type="checkbox">
<label data-bind="for: name, text: name"></label>
</script>
</body>
</html>
JS:
function MyViewModel() {
var self = this;
self.cities = ko.observableArray([]);
$.getJSON("cities.json", function(data) {
data.forEach(function (item, index) {
self.cities.push({name: item.Name, id:item.ID});
});
})
}
function DoApply() {
ko.applyBindings(new MyViewModel());
}
Where cities.json looks like:
[
{
"ID": 0,
"Name": "Bonn"
},
{
"ID": 0,
"Name": "Petrovaradin"
},
{
"ID": 0,
"Name": "Novi Sad"
},
{
"ID": 0,
"Name": "Balingen"
}
]
Live example see
here.
---
Edit: observableArray must be global, something like ns.cities = ko.observableArray([]);, and pushed should be observable:
/*global window, ko*/
(function (ns) {
"use strict";
ns.CitiesViewModel = function () {
var self = this,
getCities = new GetCities(),
city = ko.observable();
ns.cities = ko.observableArray();
function GetCities() {
$.getJSON("api/cities", function (data) {
data.forEach(function (item, index) {
city({ name: item.Name, id: item.ID });
ns.cities.push(city());
});
});
}
return {
myCities: getCities
}
}
}(window.milosev));
---
Or even better and make it part of CitiesViewModel:
/*global window, ko, $*/
(function (ns) {
"use strict";
ns.CitiesViewModel = function () {
var self = this,
getCities = new GetCities(),
city = ko.observable();
function GetCities() {
self.cities = ko.observableArray();
$.getJSON("api/cities", function (data) {
data.forEach(function (item, index) {
city({ name: item.Name, id: item.ID });
self.cities.push(city());
});
});
return self.cities;
}
return {
cities: getCities
};
};
}(window.milosev));