1

I need to create a simple comments box (just like facebook comments for example) whith knockout js. Im new to KO and I tried to search but I cant seem to find the answer to that silly question. I would spend more time but I need to finish my homework realquick. So this is my HTML:

<div id="comment-input-container">
    <input type="text" placeholder="comment..." data-bind="value: commentText">
    <button type="submit" data-bind="click: addComment">Add comment</button>
</div>  <!-- From this input I need to take the commentText and use it in the addComment function -->
<hr>

<!-- Knockout Template for showing comments -->
<div id="comment-box" data-bind="foreach: comments">
    <p data-bind="text: fullName"></p>
    <p data-bind="text: datePosted"></p>
    <div class="commentBody">
        <div class="commentContent">
            <div class="commentText" data-bind="text: commentText"></div>
            <div class="commentButtonsBox"></div>
        </div>
    </div>
</div>

And here is the JS:

function CommentsViewModel() {
    var self = this;

    self.comments = ko.observableArray([{
        fullName: "Todor Atanasov",
        datePosted: new Date(),
        commentText: "Awesome vid guys ty."}
    ]);

    self.addComment = function() {
        self.comments.push({
            fullName: "new guy",
            datePosted: new Date(),
            commentText: "new comment"
        })
    }
}

ko.applyBindings(new CommentsViewModel());

So what should I write in the place of commentText: "new comment"

  • 1
    Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Dec 10 '15 at 12:05

1 Answers1

1

Try this:

function CommentsViewModel() {
    var self = this;

    self.newComment = ko.observable(); //add this

    self.comments = ko.observableArray([{
        fullName: "Todor Atanasov",
        datePosted: new Date(),
        commentText: "Awesome vid guys ty."}
    ]);

    self.addComment = function() {
        self.comments.push({
            fullName: "new guy",
            datePosted: new Date(),
            commentText: self.newComment()
        })
    }
}

ko.applyBindings(new CommentsViewModel());

Replace this html line:

<input type="text" placeholder="comment..." data-bind="value: newComment " />
Fabio
  • 11,892
  • 1
  • 25
  • 41