访问ViewModel函数

Accessing ViewModel function

本文关键字:函数 ViewModel 访问      更新时间:2023-09-26

我正在使用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();

});

如果我的问题不清楚,请告诉我。提前感谢!

cSection是可观察的,您必须打开它才能获得commentSection实例:

vm.cSection().getNewEntries();

deleteComment功能相同:

self.deleteComment = function() {
    vm.cSection().comments.remove(self);
};