When you specify a function to be used as an event handler in jQuery, that function gets access to the raw DOM element that initiated the event as this
. So the classical solution would be to closure the class context inside the handler as self
:
class LiveViewController extends ViewController{
viewLoads(){
var self = this;
$("#mydiv")[0].addEventListener("click", function() {
self.someFunction(self);
});
}
someFunction(context){
console.log(context);
}
}
You even don't need to pass the context at all:
class LiveViewController extends ViewController{
viewLoads(){
var self = this;
$("#mydiv")[0].addEventListener("click", function() {
self.someFunction();
});
}
someFunction(){
console.log(this);
}
}
At last you may use .bind
to bind appropriate context:
class LiveViewController{
viewLoads(){
$("#mydiv")[0].addEventListener("click", this.someFunction.bind(this));
}
someFunction(){
console.log(this);
}
}
To get an access to both of instantiated object and dom element you may use
class LiveViewController extends ViewController{
viewLoads(){
var self = this;
$("#mydiv")[0].addEventListener("click", function() {
self.someFunction(this);
});
}
someFunction(element){
console.log(this);
console.log(element);
}
}