Reputation: 1508
I'm trying to write some javascript inside :javascript closure in haml template. It should show/hide divs with controls according a status which it gets over ajax call. I can't get that code running right way. I don't have a clue why. Ajax handlers success and complete aren't called. Firebug shows successful ajax request and no errors in the console. I think "self" in Thin.ajax may be broken some way.
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}");
Upvotes: 0
Views: 156
Reputation: 14219
Inside jQuery's Ajax method this
will refer to the global scope. Trying reference your parent object explicitly to make sure you are using the correct scope (your object):
function Thin() {
var that = this;
that.ajax = function() {
$.ajax({ url: "#{check_if_running_user_case_path(@user_case)}",
success: that.on_success,
error: that.on_error,
dataType: "json",
complete: that.poll,
timeout: 30000 });
}
...
Edit: Just for reference, this is a nice article on scoping this
in Javascript.
Upvotes: 1
Reputation: 557
I've had that error in firefox, so I just inlined the success method.
instead of success: this.success
I used
success:function(){},
Upvotes: 0