我需要创建一个简单的评论框(就像facebook评论一样)whith knockout js。我是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的位置写什么:&#34;新评论&#34;
答案 0 :(得分: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 " />