Denis Pshenov
Denis Pshenov

Reputation: 11327

Access External Objects From jQuery CallBack Functions

Scenario:

My_Object = {

  my_div: "#mydiv",

  my_method: function()
  {
    $(this.my_div).fadeOut("slow", function() { $(this.my_div).fadeIn("slow"); });
  }

}

'this.my_div' is not being recognized in the fadeIn call, as 'this' doesn't point to the original object anymore. How to I pass the original object to the callback function?

Upvotes: 1

Views: 437

Answers (2)

cletus
cletus

Reputation: 625057

That's because inside the fadeOut() callback, this is now the element being faded out. I assume you want to fade it back in so just do this:

My_Object = {
  my_div: "#mydiv",
  my_method: function() {
    $(this.my_div).fadeOut("slow", function() {
      $(this).fadeIn("slow"); // refers to the same object being faded out
    });
  }
}

The Javascript this concept is a little confusing.

Upvotes: 1

PanJanek
PanJanek

Reputation: 6675

Store "this" in temporary variable:

My_Object = {

  my_div: "#mydiv",

  my_method: function()
  {
    var tmp = this;
    $(this.my_div).fadeOut("slow", function() { $(tmp.my_div).fadeIn("slow"); });
  }

}

Upvotes: 2

Related Questions