I've been working on an application that relies on a static JSON array, without the support of a backend service. I've been attempting to bind this JSON array to the page using KnockoutJS. Although I can successfully load the JSON array and create the correct number of observables within a ko observableArray, I'm running into an issue where all of the observables end up empty. Despite checking my model against the JSON object setup and confirming that the JSON is loading correctly through console logging, I can't seem to figure out where I'm going wrong. Any help in identifying my mistake would be greatly appreciated.
Below is some relevant code, along with a link to a jsfiddle:
function Item(data) {
this.id = ko.observable(data.id);
this.category = ko.observable(data.category);
this.rank = ko.observable(data.rank);
this.name = ko.observable(data.name);
this.images = ko.observableArray([]);
this.price = ko.observable(data.price);
this.description = ko.observable(data.description);
}
function ChristmasListViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.selectedItem = ko.observable();
self.selectItem = function(item) {
self.selectedItem(self.items()[item]);
}
$.getJSON("https://rawgit.com/bonso/bonso.github.io/master/scripts/listitems.json", function(data) {
// var mappedItems = $.map(data, function(item) { return new Item(item) });
// self.items(mappedItems);
// console.log(self.items()[0]);
var tempArray = [];
$.each(data, function(i) {
tempArray.push(new Item(data[i]));
});
self.items(tempArray);
console.log(self.items()[0]);
});
}
$(document).ready(function() {
ko.applyBindings(new ChristmasListViewModel());
});
Fiddle: http://jsfiddle.net/8j7g08qr/1/