Reference to an object from a callback function in jQuery

ぐ巨炮叔叔 提交于 2019-12-11 01:55:47

问题


I have following situation. In a constructor of a pseudo class I attach a click event to an element. When the event is triggered I would like to refer from the callback function to the object where the event was set.

Code of the pseudo class constructor

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 to refer to the object without an global variable?


回答1:


In Javascript an anonymous function is able to reference all variables that existed at the scope of the function's creation. Since this gets reassigned in the callback function, you can create a local variable to store it before you enter the callback.

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

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

}



回答2:


This is better documented in the jQuery API. jQuery Bind

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

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

I hope this helps!



来源:https://stackoverflow.com/questions/1579672/reference-to-an-object-from-a-callback-function-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!