Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call JavaScript class instance method from DOM event?

I have the following simple JavaScript "class":

function Person(params) 
{
    this.name = params.name;
}
Person.prototype.SayHi = function()
{
    alert(this.name + " says hi");
}

This works as expected when I run it in place. Running the following code gives me a popup that says "Alice says hi":

var alice = new Person({name:"Alice"});
alice.SayHi();

But when I try to assign it to a button event, it won't work:

$("#AliceOnClick").on("click", alice.SayHi);
$("#BobOnClick").on("click", bob.SayHi);

It appears that the SayHi function gets called, but the name field is null.

Minimal working example:

http://jsfiddle.net/AKHsc/1/

What am I doing wrong?

like image 393
Jay Sullivan Avatar asked Dec 01 '22 20:12

Jay Sullivan


2 Answers

jQuery sets the receiver of the event handler to the target element, so that you can conveniently do something like $(this).hide().

You can use e.g. $.proxy to work around it:

$(function(){
    $("#AliceOnClick").on("click", $.proxy(alice.SayHi, alice));
    $("#BobOnClick").on("click", $.proxy(bob.SayHi, bob));
});
like image 68
Esailija Avatar answered Dec 03 '22 10:12

Esailija


Just run it in an anonymous function to invoke it. Since you're calling a method on the object, you need parenthesis.

$(function(){
    $("#AliceOnClick").on("click", function() {
        alice.SayHi();
    });
    $("#BobOnClick").on("click", function() {
        bob.SayHi();
    });
});

Working Fiddle here.

like image 39
Seth Avatar answered Dec 03 '22 08:12

Seth