Reputation: 5338
I want to call a function on the click event, my collegue defined the function as written below. Somehow I cannot access it, what is wrong?
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
});
}
Upvotes: 0
Views: 872
Reputation: 316
In an event handler bound with jQuery, this
refers to the DOM element on which the handler was bound. See jQuery Event Basics.
You can override jQuery's this
binding by using function#bind
on the click handler:
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
}.bind(this));
}
Beware of browser support for function#bind
-- if you target older browsers you'd need a polyfill or simply assign the value of this
to another variable.
Upvotes: 1
Reputation: 33880
this
in a click function is the clicked element. Save a reference of the object in a variable outside the function and use it :
function Start(data) {
var self = this; //HERE
this.move= function() {
....
};
$('.button').click(function(){
self.move();
});
}
Here's an article that may give you more explanation about the above fix.
Upvotes: 3
Reputation: 207527
Another way to keep the scope is to use jQuery's proxy()
$('.button').click($.proxy(this.move, this));
Upvotes: 1
Reputation: 11620
try this, you must remember reference to your main function.
function Start(data) {
var that = this;
this.move = function() {
....
};
$('.button').click(function(){
that.move();
});
}
Upvotes: 1