【问题标题】:Unable to get the correct context with bind() using a promise使用 promise 无法通过 bind() 获得正确的上下文
【发布时间】:2014-06-16 14:40:14
【问题描述】:

我无法使用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() 语句输出正确的上下文(此对象),但 updateGenerationProgress() 内的 console.log() 语句输出 Window 作为上下文。为什么是这样?关于承诺和上下文,我有什么遗漏吗?

【问题讨论】:

    标签: javascript ajax oop requirejs promise


    【解决方案1】:

    你也需要在间隔上设置上下文

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

    否则,那里的上下文在非严格模式下设置为window(或工作人员),在严格模式下设置为undefined

    【讨论】:

    • 哇,不敢相信我忽略了这一点。太感谢了!这解决了一切。
    • @Aaron 很高兴我能提供帮助,我个人会将从服务器获取内容的逻辑与更新 DOM 的逻辑分开。
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多