Durandal & Knockout:在 ajax 请求时禁用按钮

Durandal & Knockout: Disable Button while ajax Request

我有多个绑定点击事件的按钮:

<button type="button" class="btn btn-primary pull-right"
    data-bind="click: clickAction.bind($data, 'start')">Start
</button>

clickAction 执行一些 ajax 查询,具体取决于给定的参数 ("start")。现在我想在加载请求时禁用此按钮... 我怎样才能像这样访问 属性:

// pseudo code
function clickAction(actionType) {
    $(senderButton).prop('disabled', true);
    // HERE SOME AJAX STUFF
    $(senderButton).prop('disabled', false);
}

编辑: 我用淘汰赛 'enabled' 绑定做到了:

<button type="button" class="btn btn-primary pull-right"
    data-bind="click: clickAction.bind($data, 'start'), enable: !isLoading()">Start
</button>

像这样改变你的看法:

 <button type="button" class="btn btn-primary pull-right"
    data-bind="click: clickAction.bind($data, 'start'), disable: ajaxInProgress">Start
</button>

然后在您的视图模型中,定义一个 ajaxInProgress 可观察对象:

var ajaxInProgress = ko.observable(false);

您还需要在视图模型中公开该可观察对象。

在您的 clickAction 事件处理程序中,您需要在发送 AJAX 请求之前将 observable 设置为 true,然后在响应为 false 时返回 false收到:

this.clickAction = function (actionType) {
    ajaxInProgress(true);
    // possibly incorrect jQuery AJAX call syntax...
    $.get({
        // ... URL, method, and other params ...
        success: function () {
            ajaxInProgress(false);
            // ... other actions when data is loaded ...
        },
        error: function () {
            ajaxInProgress(false);
            // ... other error handling ...
        }
    });
}

请注意,我没有在 $.get 调用之后的行上执行 ajaxInProgress(false),因为那是在请求发送后立即发生的,而不是等到收到响应。它必须在回调中。