0

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.

2
  • Could you provide a working example, e.g. on jsfiddle? Commented Jan 3, 2015 at 15:26
  • apagar.addEventListener('click', cl.teste.bind(cl), false); Commented Jan 3, 2015 at 15:34

2 Answers 2

4

You can use bind in this situation:

apagar.onclick = cl.teste.bind(cl);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

4 Comments

Yes, onclick is an event handler, not a property!
yea i just did that before reading this post ! ty for help :) it worked !
It's not entirely clear from the question, but I think this.doentes.length is a property on cl. So you would use cl.teste(cl) here, not cl.teste(apagar).
i used: apagar.addEventListener('click', function () { cl.removerDoente(this);});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.