【问题标题】:Success handler for ko.applyBindingsko.applyBindings 的成功处理程序
【发布时间】:2014-01-28 18:10:48
【问题描述】:

我有一段代码要在 applyBindings 成功完成后执行。

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

由于异步执行,有时dependantMethod() 执行得更快。有没有办法查出 ko.applyBindings 是否执行成功,这样我就可以把dependantMethod();在成功处理程序内部?

谢谢。

【问题讨论】:

  • applyBindings 不是异步的,因此在您的代码示例中,dependantMethod 始终在applyBindings 成功执行后执行。 applyBindings 可能会触发一些异步操作,但我们需要查看您的 myViewModel 代码。
  • 你能根据你的结果关闭/删除问题吗

标签: javascript knockout.js


【解决方案1】:

如果没有查看您的视图模型,很难完全回答,但您可能需要考虑在您的视图模型中使用 knockout subscribe 函数。

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

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(); 
    };
}

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多