How to get the this of a object in a handler for a

2019-01-20 18:48发布

问题:

// 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) );


标签: jquery scope