Reputation: 6962
I'm new to KnockOut. I've followed along the tutorial on there site and I'm now trying to use that knowledge in my project for school.
Unfortunately I'm stuck. I want to dynamically fill my text from a local JSON file. I have debugged and my code for fetching the data works, but doesn't show on my HTML page.
A piece of my View:
<p data-bind="text: level.assignment">
replace dynamically
</p>
KnockOut is connected to my HTML because other bindings work. My ViewModel
//Class to represent the Level
function Level(id, assignment, videoURL) {
var self = this;
self.id = id;
self.assignment = assignment;
self.videoURL = videoURL;
}
function LevelViewModel(id) {
//Data
var self = this;
self.id = id;
self.level = ko.computed(function () {
//fetching the local json
$.get('/Data/Text2Speech.json', "", function (data, textStatus, jqXHR) {
if (textStatus != "success") {
return "not found";
}
//Make the level object
self.level = new Level(data.exercise[self.id - 1].id, data.exercise[self.id - 1].assignment, data.exercise[self.id - 1].videoURL);
return self.level;
});
}, this);
};
The debugging window.
What am I doing wrong? Thanks
My JSFiddle http://jsfiddle.net/pPZ48/
Upvotes: 1
Views: 84
Reputation: 6962
The solution was found by Aneesh A.E. He saw that the $.get() function from JQuery was Async. So here is the correct code:
//Class to represent the Level
function Level(id, assignment, videoURL) {
var self = this;
self.id = id;
self.assignment = assignment;
self.videoURL = videoURL;
}
function getRemoteFile() {
return $.ajax({
type: "GET",
url: '/Data/Text2Speech.json',
async: false,
success: function () {
console.log("Success");
},
error: function () {
console.log("Error");
}
}).responseText;
}
function LevelViewModel(id) {
//Data
var self = this;
self.id = id;
self.level = ko.computed(function () {
//fetching the local json
data = JSON.parse(getRemoteFile());
self.level = new Level(data.exercise[self.id - 1].id, data.exercise[self.id - 1].assignment, data.exercise[self.id - 1].videoURL);
return self.level;
}, this);
};
As well as changing the HTML to
<p data-bind="text: level().assignment">
replace dynamically
</p>
Upvotes: 1