Reputation: 185
How to call method Go from inside a event handler?
function Test()
{
this.yo = "YO";
this.Go = function()
{
alert(this.yo);
}
$(".aha").click(function()
{
//Call Go();
});
}
var test = new Test();
Fiddle: http://jsfiddle.net/BkNfY/9/
Upvotes: 2
Views: 4866
Reputation:
The jQuery way :
$('.aha').click($.proxy(function (e) {
// e.target refers to the clicked element
this.Go();
}, this));
Shorter :
$('.aha').click($.proxy(this.Go, this));
$('.aha').click($.proxy(this, 'Go'));
http://api.jquery.com/jQuery.proxy/
Upvotes: 0
Reputation: 4530
function Test(){
var that = this;
that.yo = "YO";
that.go = function(){
alert(that.yo);
}
$(".aha").click(function(){
that.go();
});
return that;
}
var test = new Test();
but it would make more sense to do it like this: (if you want to reuse Test)
function Test(){
var that = this;
that.yo = "default YO";
that.go = function(){
alert(yo);
}
return that;
}
var test = new Test();
test.yo = "YO";
$(".aha").click(function(){
test.go();
});
You could keep yo "private" if it is not going to be used outside of Test, e.g. test.yo
function Test(){
var that = this,
yo = "YO"; // yo is now "private"
// so can't modify yo from outside of this function
that.go = function(){
alert(yo);
}
return that;
}
var test = new Test();
$(".aha").click(function(){
test.go();
});
Upvotes: 3
Reputation: 150010
A common method is to have a local variable in your constructor that is a reference to the instance:
function Test()
{
var self = this;
this.yo = "YO";
this.Go = function(){
alert(this.yo);
}
$(".aha").click(function(){
self.Go();
});
}
Or you can bind the function you pass to .click()
:
$(".aha").click(function(){
this.Go();
}.bind(this));
Upvotes: 3