我需要在第一页加载时向用户显示最后评论,如添加新评论后,新评论成功添加到可观察数组但我无法显示最后评论,我正在尝试此代码,但它不起作用。
我的代码附在JsFiddle
中
function Comment(NoteText, CreateDate) {
this.commentText = ko.observable(NoteText);
this.createDate = ko.observable(CreateDate);
}
function CommentList() {
var nm = this;
nm.newComment = ko.observable();
nm.allComments = ko.observableArray([{ commentText: 'Hellow world', createDate: 'some date' }]);
nm.AddNewComment = function () {
nm.allComments.push(new Comment(this.newComment(), Date()));
this.newComment('');
}
ko.applyBindings(nm, document.getElementById("comments"));
}
var comments = new CommentList();
$("#allcomments").hide();
$("#btnViewAll").click(function () {
$("#allcomments").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="comments">
<input type="text" data-bind="value:newComment" /><button data-bind="click: AddNewComment">Add New Comment</button><br />
<hr />
Last Comment: <strong> <span data-bind="text: allComments[allComments.length-1]"></span> </strong><button id="btnViewAll">View ALL</button>
<br />
<div id="allcomments">
<h2>All Comments</h2>
<table>
<thead>
<tr>
<td>Comment Text</td>
<td>Date</td>
</tr>
</thead>
<tbody data-bind="foreach: allComments">
<tr>
<td><span data-bind="text: commentText"></span></td>
<td><span data-bind="text: createDate"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
答案 0 :(得分:0)
allComments
是一个可观察的数组,因此您需要使用括号来获取它为表达式包含的数组
"text: allComments()[allComments().length-1]"
为清楚起见,制作计算名为lastComment
并在绑定中使用它可能更好。