Referencing an object from a callback function in jQuery

I have the following situation. In the constructor of the pseudo class, I attach a click event to the element. When the event fires, I would like to call from the callback function to the object where the event was set.

Pseudo-class constructor code

function MyClass(){
  this.myClassAttribute = "A class attribute";

  // here `this` refers to the object

  $("span").click(function(){
    // here `this` refer to a matched element, i.e. "span"
    // How to get the value of `myClassAttribute`?
  });

}

      

How can I refer to an object without a global variable?

+2


source to share


2 answers


In Javascript, an anonymous function can refer to all variables that exist in the scope of the function creation. Since it this

gets reassigned in the callback function, you can create a local variable to store it before injecting the callback.



function MyClass(){
  this.myClassAttribute = "A class attribute";
  var myClass = this;

  $("span").click(function(){
    myClass.myClassAttribute = "hello";
  });

}

      

+12


source


This is better described in the jQuery API. jQuery Bind

$. click is just a shortcut to $ .bind ('click', / no data /, callback)



$('span').bind('click', { parentObj: this }, function(e) {
  var parentObj = e.data.parentObj;
  // the rest of your code goes here
}

      

Hope this helps!

+8


source







All Articles