我正在尝试在haml模板中编写一些javascript:javascript闭包。它应该根据通过 ajax 调用获得的状态显示/隐藏带有控件的 div。我无法让该代码以正确的方式运行。我不知道为什么。不调用 Ajax 处理程序成功和完成。Firebug 在控制台中显示成功的 ajax 请求并且没有错误。我认为 Thin.ajax 中的“自我”可能会以某种方式被破坏。
function Thin() {
this.ajax = function() {
$.ajax({ url: "#{check_if_running_user_case_path(@user_case)}", success: this.on_success, error: this.on_error, dataType: "json", complete: this.poll, timeout: 30000 });
}
this.poll = function() {
alert("poll");
setTimeout(this.ajax, 2000);
};
this.manage_divs = function(st) {
if (st != this.running) {
if (st == "running") {
this.hide_div_arr_show_div([this.start_div, this.starting_div, this.stopping_div], this.stop_div);
} else if (st == "starting"){
this.hide_div_arr_show_div([this.start_div, this.stop_div, this.stopping_div], this.starting_div);
} else if (st == "stopping"){
this.hide_div_arr_show_div([this.start_div, this.stop_div, this.starting_div], this.stopping_div);
} else {
this.hide_div_arr_show_div([this.stopping_div, this.stop_div, this.starting_div], this.start_div);
}
this.running = st;
}
};
this.setup = function(start_div, starting_div, stop_div, stopping_div) {
this.start_div = start_div;
this.starting_div = starting_div;
this.stop_div = stop_div;
this.stopping_div = stopping_div;
// set as stopped
this.running = "12345";
this.poll();
};
this.on_error = function(jqXHR, textStatus, errorThrown){
alert(["Thin polling error", textStatus]);
};
this.on_success = function(data, textStatus, jqXHR) {
alert("success!");
var st = data.user_case;
this.manage_divs(st);
};
this.hide_div_arr_show_div = function(div_arr, div){
for(var i = 0; i < div_arr.length; i++)
div_arr[i].hide();
div.show();
};
};
var thin = new Thin();
thin.setup($("#user_case_stopped"), $("#user_case_starting"), $("#user_case_running"), $("#user_case_stopping"));
thin.manage_divs("#{@running}");