我正在使用knockout来制作一个评论字段,我已经从使用几个视图模型更改为一个父视图模型,因为我在使用foreach时遇到了一些冲突。我的新问题是从我的父ViewModel运行一个函数。我的Comment()函数有效,但我在javascript中调用commentSection()时遇到问题。
我想从函数commentSection调用getNewEntries。我认为这样做的方法是使用vm.cSection.getNewEntries调用我的Viewmodel(vm),但控制台说它不是一个函数。所以我的问题是,如何通过vm调用此函数getNewEntries?
以下是它的外观:
function Comment() {
var self = this;
self.nickname = ko.observable();
self.newMsg = ko.observable("");
self.sendEntry = function() {
if (self.newMsg() !== "" && self.nickname() !== "") {
$.post(writeUrl, "entry=" + ko.toJSON(self));
self.newMsg("");
}
};
}
function commentSection() {
var self = this;
self.timestamp = 0;
self.comments = ko.observableArray();
self.editable = ko.observable(false);
self.deleteComment = function() {
vm.cSection.comments.remove(self);
};
self.editComment = function() {
self.editable(!self.editable());
};
self.getNewEntries = function() {
$.getJSON(readUrl, "timestamp=" + self.timestamp, function(comments) {
for (var i = 0; i < comments.length; i++) {
var entry = comments[i];
if (entry.timestamp > self.timestamp) {
self.timestamp = entry.timestamp;
}
self.comments.unshift(entry);
}
self.getNewEntries();
});
};
}
function ViewModel() {
var self = this;
self.cSection = ko.observable(new commentSection());
self.comments = ko.observableArray();
self.selectedComment = ko.observable(new Comment());
//self.cSection.getNewEntries();
}
var vm = new ViewModel();
ko.applyBindings(vm);
vm.cSection.getNewEntries();
});
如果我的问题不清楚,请告诉我。提前谢谢!
答案 0 :(得分:0)
cSection
是一个可观察的,您必须打开它以获取commentSection
实例:
vm.cSection().getNewEntries();
deleteComment
函数中的相同内容:
self.deleteComment = function() {
vm.cSection().comments.remove(self);
};