Pedro Costa
Pedro Costa

Reputation: 437

JavaScript onclick event doesnt work with parameters

So i have a button with this event attached:

apagar.onclick = cl.teste(this);

cl is an instance of another class , i think it doesnt matter to this case. The teste method is here:

Clinica.prototype.teste = function ()
{
    alert(this.doentes.length);
}

even when i have some parameters on the function, and i set them on the onclick event, the button just does nothing. But, when i set it like this: apagar.onclick = cl.teste; it works. I need the arguement because i need the 'this' statement to work properly for the object and not for the event.

Upvotes: 0

Views: 62

Answers (2)

Nicola Ferraro
Nicola Ferraro

Reputation: 4189

Instead of writing:

apagar.onclick = cl.teste(this);

You can write:

apagar.onclick = function () {
    cl.teste(apagar);
};

The onclick event can be attached to a function not to a function-call. Here cl.teste is a function, while cl.tests(this) is a function call. With my workaround, it should work.

Upvotes: 3

JLRishe
JLRishe

Reputation: 101690

You can use bind in this situation:

apagar.onclick = cl.teste.bind(cl);

Upvotes: 4

Related Questions