Totty.js
Totty.js

Reputation: 15831

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

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

Upvotes: 0

Views: 186

Answers (3)

user113716
user113716

Reputation: 322502

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

Upvotes: 1

Phrogz
Phrogz

Reputation: 303251

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.
};

Upvotes: 1

David Tang
David Tang

Reputation: 93684

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

Upvotes: 1

Related Questions