How to get the this of a object in a handler for a click event in jquery?

徘徊边缘 提交于 2019-12-17 21:19:27

问题


// begin signals
this.loginSignal

this.init = function(){
  // init signals
  this.loginSignal = new t.store.helpers.Signal;

  // map events
  $('[value]="login"', this.node).click(this.login)
}

this.login = function(){
  // this will dispatch an event that will be catched by the controller
  // but this is not refering to this class
  // and the next line fails :s
  this.loginSignal.dispatch();
}

to make it work now i must add

var $this = this;

this line and use $this instead of this :S

any clearer way around? thanks


回答1:


When the click handler is called, the this keyword is remapped to the element that triggered the event. To get to the original object, you want to put the function code in a closure, and make a reference to the object outside the closure, where you still have the correct reference to this.

  // map events
  var thisObject = this;
  $('[value]="login"', this.node).click(function () {
     thisObject.loginSignal.dispatch();
  });



回答2:


Technique 1: Use a Closure

var me = this;
$(...).click(function(){ me.login(); });

Technique 2: Get the element that handled the event

this.login = function(evt){
  var el = evt.currentTarget || evt.target || evt.srcElement;
  // Do something with the element here.
};



回答3:


jQuery has a method called jQuery.proxy() that is used to return a function with the value of this set to what you want.

$('[value="login"]', this.node).click( $.proxy(login, this) );


来源:https://stackoverflow.com/questions/4466524/how-to-get-the-this-of-a-object-in-a-handler-for-a-click-event-in-jquery

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