ko.applyBindings的成功处理程序

Success handler for ko.applyBindings

本文关键字:处理 程序 成功 applyBindings ko      更新时间:2023-09-26

我有一段代码,它将在applyBindings成功完成后执行。

var vmObject = new myViewModel();
ko.applyBindings(vmObject, document.getElementById('page1'));
dependantMethod();

由于异步执行,有时dependentMethod()执行得更快。有没有办法知道ko.applyBindings是否已经成功执行,这样我就可以放dependentMethod();成功处理程序内部?

谢谢。

如果没有看到您的视图模型,很难完全回答,但您可能需要考虑在视图模型中使用淘汰订阅功能。

如果你的视图模型中有一个可观察或可观察的数组,你可以订阅它的更改,并验证它是否具有预期值,然后从那里调用你的依赖函数。

var myViewModel = function () {
    var self = this;
    self.myArray = ko.observableArray([]);
    // some code that populates the array
    var subscription = self.myArray.subscribe(function (arr) {
        // some check on the observable
        if (arr.length > 0) {
            self.dependantMethod();                                
        }
    });
    self.dependantMethod = function () {
        // execute your code
        // posibly dispose of the subscription if you don't want 
        // it called multiple times
        subscription.dispose(); 
    };
}