views:

38

answers:

2

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' doest point to the original object anymore. How to I pass the original object to the callback function?

A: 

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"); });
  }

}
PanJanek
+1  A: 

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.

cletus