Tribhuwan
Tribhuwan

Reputation: 180

knockout template parsing of json data is not working

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));
​

Upvotes: 0

Views: 459

Answers (1)

nemesv
nemesv

Reputation: 139778

You have multiple problems with your code some are related to KnockOut some of them are not:

Which are not related to KO:

  • In BlogViewModel the self variable should hold this not the data parameter: so it should be var self = this;
  • Your comment mapping is wrong: the new Comment(com.commenter, com.comment) should be new Comment(com)

Which are related to KO:

  • The value binding is used for input elements, you have labels so you need to use the text binding instead. E.g data-bind="text: title"
  • KO needs valid html. Because the self-closing label tag 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.

Upvotes: 1

Related Questions