javascript - 无法使用 Promise 通过 bind() 获取正确的上下文

标签 javascript ajax oop requirejs promise

我无法使用 bind() 在我的内部函数之一中获取正确的上下文。这是我的代码:

return {
    /**
     * Checks if the table loader is active
     * @return {home} Returns this module for chaining
     */
    loadStatusLog: function() {
        if ($("#status-log-box").length) {
            $.getJSON("/Home/CurrentEvents", function(json, status, xhr) {
                if (status === "error") {
                    var errmsg = "Sorry but there was an error: ";
                    $("#result-msg").html(errmsg + xhr.status + " " + xhr.statusText);
                }
                else if (status === "success") {
                    if (json.globalGenerationStatus) {
                        console.log(this);
                        this.updateProgressInterval = setInterval(this.updateGenerationProgress, 1000);
                    }
                    var html = statusLog(json);
                    $("#status-log-table").html(html);
                }
            }.bind(this));
        }
        return this;
    },
    /**
     * Looks at the generation progress file and updates the progress bar for a running event
     * @returns {home} Returns this module for chaining
     */
    updateGenerationProgress: function() {
        var runningEvent = $(".running-event");
        $.ajax({
            type: "POST",
            url: "/Home/readGenerationStatusFile",
            global: false
        }).done(function(data) {
            runningEvent.css("width", data + "%").attr("aria-valuenow", data);
            if (data === "100") {
                console.log(this);
                clearInterval(this.updateProgressInterval);
                $("span", runningEvent).text("Complete").parent().removeClass("running-event").parent().removeClass("active progress-striped");
            }
        }.bind(this));
        return this;
    }

};

我的主要目标是从 updateGenerationProgress() 函数中清除 loadStatusLog() 函数内部设置的间隔。 loadStatusLog() 内部的 console.log() 语句输出正确的上下文(此对象),但内部的 console.log() 语句updateGenerationProgress() 的输出 Window 作为上下文。为什么是这样?我对 promise 和背景有什么遗漏吗?

最佳答案

您还需要设置间隔的上下文

this.updateProgressInterval = 
    setInterval(this.updateGenerationProgress.bind(this), 1000);

否则,在非严格模式下,上下文将设置为 window(或工作线程),在严格模式下,将设置为 undefined

关于javascript - 无法使用 Promise 通过 bind() 获取正确的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24246219/

相关文章:

javascript - Android 浏览器 html5 音频无法播放

Javascript - 在音轨中的确切位置时将音频搜索到特定位置

javascript - 使用 javascript/jquery 在 html 表中动态添加 csv 中的值

c++ - 将类的属性泄露给它的组件

python - 与类相同类型的类变量

javascript - React组件继承和ajax调用

javascript - 通过 python 脚本发送包含 javascript 的动态 html 电子邮件

javascript - 排队多个 AJAX 请求,等待响应而不卡住浏览器?

php - jQuery - 追加 ajax 结果

java - 查找对象引用