【发布时间】: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