bergman
bergman

Reputation: 185

Call function inside event handler oop

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

Answers (3)

user1636522
user1636522

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

sanchez
sanchez

Reputation: 4530

http://jsfiddle.net/BkNfY/12/

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

nnnnnn
nnnnnn

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

Related Questions