如何从输入字段中获取值并将其分配给视图模型中的JavaScript对象

How to take value from input field and assign it to a JavaScript object in your view model?

本文关键字:视图 分配 模型 对象 JavaScript 输入 字段 获取      更新时间:2023-09-26

我需要创建一个带有knocket 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:"new comment"

的位置写些什么呢

试试这个:

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 " />