Nicc Nicc - 1 month ago 4
Javascript Question

Access a specific element clicked

I have the following method

PMm.test = function (){
....plenty of code....

$('.element',this.page).click(function(e){
e.preventDefault();
var self = $(this);
console.log(self);
this.load(someoptions)
}.bind(this));

...plenty of code....

}

PMm.test.prototype.load = function(options){
...some code
}


When
console.log(self)
, it returns the method
PMm.test
. How do i access the element clicked if
$(this)
is the entire function scope where i declare my event ? Knowing that i also need to call the
.load()
method which is declared later on.

Answer

I think it'd be best to store the context in a variable an access it using closure in your callback. It'd lead to a more readable code.

PMm.test = function (){
  ....plenty of code....
  // Store the context in a variable.    
  var that = this;
  $('.element',this.page).click(function(e){
    e.preventDefault();
    // this here references the DOM element (as expected)
    var self = $(this);
    console.log(self);
    // you can access your methods through that.
    that.load(someoptions)
  });

  ...plenty of code....

}

PMm.test.prototype.load = function(options){
  ...some code
}

Hope it helps.