vuvu
vuvu

Reputation: 5338

jQuery - undefined function call on click

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

Answers (4)

John Madhavan-Reese
John Madhavan-Reese

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

Karl-André Gagnon
Karl-André Gagnon

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

epascarello
epascarello

Reputation: 207527

Another way to keep the scope is to use jQuery's proxy()

$('.button').click($.proxy(this.move, this));

Upvotes: 1

Beri
Beri

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

Related Questions