Please check this link is not working, i have no idea what is wrong in my code.
I am trying to create a blog application, which have title, description and comments, but i am not getting proper output.
<h4>Title</h4>
<label data-bind="value: title" />
<h4>Description</h4>
<label data-bind="value: description" />
<h4>Comments</h4>
<p data-bind="foreach: comments">
<label data-bind="value: commenter" /><br>
<label data-bind="value: comment" /><br>
</p>
var data = {"title": "blog1",
"description": "Description1",
"comments": [{"commenter": "commenter1", "comment": "comment1"},
{"commenter": "commenter2", "comment": "comment2"},
{"commenter": "commenter3", "comment": "comment3"},
{"commenter": "commenter4", "comment": "comment4"}]};
function Comment(data) {
this.commenter = ko.observable(data.commenter);
this.comment = ko.observable(data.comment);
}
function BlogViewModel(data) {
var self = data;
self.title = data.title;
self.description = data.description;
self.comments = ko.observableArray(ko.utils.arrayMap(data.comments, function (com) {
return new Comment(com.commenter, com.comment);
}));
}
ko.applyBindings(new BlogViewModel(data));
You have multiple problems with your code some are related to KnockOut some of them are not:
Which are not related to KO:
BlogViewModeltheselfvariable should holdthisnot thedataparameter: so it should bevar self = this;new Comment(com.commenter, com.comment)should benew Comment(com)Which are related to KO:
valuebinding is used forinputelements, you have labels so you need to use the text binding instead. E.gdata-bind="text: title"labeltag is not valid you need to add the closing tags to your labels e.g<label data-bind="text: description"></label>Here is a working JSFiddle containg all the fixes.