1

我需要使用淘汰赛 js 创建一个简单的评论框(就像 facebook 评论一样)。我是 KO 的新手,我试图搜索,但我似乎找不到那个愚蠢问题的答案。我会花更多的时间,但我需要尽快完成我的作业。所以这是我的 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>

这是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());

那么我应该在commentText的地方写什么:“新评论”

4

1 回答 1

1

尝试这个:

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

替换此 html 行:

<input type="text" placeholder="comment..." data-bind="value: newComment " />
于 2015-12-10T12:12:21.853 回答