【发布时间】:2015-11-28 23:05:09
【问题描述】:
所以我正在尝试将内容添加到可观察数组,但它没有更新。问题不是第一级内容,而是子数组。这是一个小的 cmets 部分。 基本上我有这个函数来声明 cmets
function comment(id, name, date, comment) {
var self = this;
self.id = id;
self.name = ko.observable(name);
self.date = ko.observable(date);
self.comment = ko.observable(comment);
self.subcomments = ko.observable([]);
}
我有一个通过id 字段检索对象的函数
function getCommentByID(id) {
var comment = ko.utils.arrayFirst(self.comments(), function (comment) {
return comment.id === id;
});
return comment;
}
这是我展示我的 cmets 的地方
<ul style="padding-left: 0px;" data-bind="foreach: comments">
<li style="display: block;">
<span data-bind="text: name"></span>
<br>
<span data-bind="text: date"></span>
<br>
<span data-bind="text: comment"></span>
<div style="margin-left:40px;">
<ul data-bind="foreach: subcomments">
<li style="display: block;">
<span data-bind="text: name"></span>
<br>
<span data-bind="text: date"></span>
<br>
<span data-bind="text: comment"></span>
</li>
</ul>
<textarea class="comment" placeholder="comment..." data-bind="event: {keypress: $parent.onEnterSubComment}, attr: {'data-id': id }"></textarea>
</div>
</li>
</ul>
而onEnterSubComment是有问题的事件形式
self.onEnterSubComment = function (data, event) {
if (event.keyCode === 13) {
var id = event.target.getAttribute("data-id");
var obj = getCommentByID(parseInt(id));
var newSubComment = new comment(0, self.currentUser, new Date(), event.target.value);
obj.subcomments().push(newSubComment);
event.target.value = "";
}
return true;
};
这很有趣,因为当我在初始化期间(在任何函数之外)尝试相同的操作时,它工作正常
var subcomment = new comment(self.commentID, "name1", new Date(), "subcomment goes in here");
self.comments.push(new comment(self.commentID, "name2", new Date(), "some comment goes here"));
obj = getCommentByID(self.commentID);
obj.subcomments().push(subcomment);
如果有人可以帮助我解决这个问题,因为我有点卡住了:(
【问题讨论】:
-
速成:也许是
self.subcomments = ko.observableArray([])而不是self.subcomments = ko.observable([])? jsfiddle 上的演示总是一个好主意...
标签: javascript html knockout.js knockout-templating