[英]Unable to get the correct context with bind() using a 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;
}
};
我的主要目标是明确的间隔内设置loadStatusLog()
从功能updateGenerationProgress()
函数。 所述console.log()
的内部语句loadStatusLog()
输出正确的上下文(此目的),但console.log()
的内部语句updateGenerationProgress()
输出窗口作为上下文。 为什么是这样? 关于承诺和上下文,我缺少什么吗?
您还需要在间隔上设置上下文
this.updateProgressInterval =
setInterval(this.updateGenerationProgress.bind(this), 1000);
否则,那里的上下文将在非严格模式下设置为window
(或工作程序),而在严格模式下设置为undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.