【问题标题】:Update multiple subscribables, but only execute update once in knockout?更新多个可订阅,但在淘汰赛中只执行一次更新?
【发布时间】:2016-09-30 16:06:31
【问题描述】:

我有一个包含多个淘汰组件的应用程序。淘汰组件都绑定到一组可订阅,这些订阅会在单击按钮时更新。每个组件都有几个订阅函数来监听订阅者的变化以调用其中包含的更新函数。

如何将它们配置为仅在更新多个订阅者时调用其更新函数一次?

这是我的大多数组件如何加载的示例 sn-p:

this.OBSERVABLE_NAME.subscribe(function () { this.updateChart(); }, this);
this.OBSERVABLE_NAME.subscribe(function () { this.updateChart(); }, this);
this.OBSERVABLE_NAME.subscribe(function () { this.updateChart(); }, this);
this.OBSERVABLE_NAME.subscribe(function () { this.updateChart(); }, this);

this.updateChart = function () {
    $.ajax({
        type: "POST",
        traditional: true,
        url: this.ajax_location,
        data: this.ajax_parameters,
        success: function (data) {
            // DO SOMETHING
        }.bind(this),
        error: function (returndata) {
            alert("Error:\n" + returndata.responseText);
        }
    });
};

但是,如果我将订阅函数替换为:

ko.computed(function () {
        $.ajax({
        type: "POST",
        traditional: true,
        url: this.ajax_location,
        data: this.ajax_parameters,
        success: function (data) {
            // DO SOMETHING
        }.bind(this),
        error: function (returndata) {
            alert("Error:\n" + returndata.responseText);
        }
    });
}, this).extend({ throttle: 1 });

它似乎按要求工作。我知道油门已贬值,但我很好奇为什么 deferred 似乎无法正常工作。

【问题讨论】:

  • 你有一些示例代码吗?这听起来像是延迟更新的一个可能用例,但如果没有代码 sn-p 或示例就很难说。
  • 我已经用代码示例更新了问题。

标签: javascript knockout.js


【解决方案1】:

没有具体的例子很难说,但我认为您正在寻找deferred updates

您可以使用 .extend({ deferred: true }) 扩展可观察对象

【讨论】:

  • 奇怪的是,延迟更新似乎无法解决问题,但节流可以解决。
【解决方案2】:

看起来这对于限制或延迟更新很有用。就我而言, deferred 似乎无法正常工作,但节流却可以。我使用以下sn-p:

ko.computed(function () {
        $.ajax({
        type: "POST",
        traditional: true,
        url: this.ajax_location,
        data: this.ajax_parameters,
        success: function (data) {
            // DO SOMETHING
        }.bind(this),
        error: function (returndata) {
            alert("Error:\n" + returndata.responseText);
        }
    });
}, this).extend({ throttle: 1 });

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多