I've just decided to learn knockoutjs, and I'm having a bit of an issue binding some json to my viewmodel. I've searched heaps on it, tried heaps of things, but I must have missed something.
Javascript:
var data = {
"TestList": [{ "ID": "1", "Name": "Dave" }, { "ID": "2", "Name": "Mustaine" }],
"TestText": "Hello World"
};
var viewModel = {};
ko.mapping.fromJSON(data, viewModel);
ko.applyBindings(viewModel);
HTML
TestText: <span data-bind="text: TestText"></span><br>
TestList: <select id="TestList"
data-bind="
options: TestList,
optionsText: 'Name',
optionsValue: 'ID',
optionsCaption: 'Please Select'"></select>
EDIT
the variable 'data' was used as an example of the json I get back from the server. Anyways, I've updated the above code with getJSON and getting an error which the above example really can't give me as it doesn't use getJSON.
Updated JAVASCRIPT:
var viewModel;
$.getJSON('/myurl',
function (data) {
viewModel = data;
});
alert(viewModel);
$(function() {
ko.applyBindings(viewModel);
});
The issue i'm having here is that it works.. as long as the alert box is there. If i comment that line out, it doesn't work!