Javascript onclick/addeventlistener with no anonymous function

Asked

Viewed 229 times

1

I have a problem with javascript onclick/addeventlistener, I have tried several different ways and no results were found, I wanted my click event to be equal to a function already declared and not equal to an anonymous function, but I’m not getting to do it cleanly in the code.

What I need is:

botao.onclick = criaObjeto(parametro);

function criaObjeto(parametro) {
    //cria objeto
}

or

botao.addEventListener("click", criaObjeto(parametro));

function criaObjeto(parametro){
    //cria objeto
}

Neither of these two ways worked, I really wouldn’t want to do something like:

botao.onclick = function (){
    criaObjeto(parametro);
)};

Because it breaks the idea of clean code, but none of the alternatives I tried worked, it just doesn’t recognize the event. The click event happens as soon as the application starts and does not work later, so it does not work as a click, but as a normal function declared in the scope of the code.

The terminal does not trigger any errors at any time.

1 answer

2


You have to create a function that returns another, or you do bind of that argument you need to use.

#1 - criaObjeto returns a function

function criaObjeto(param){
    return function(evento){ // <-- esta função será chamada pelo `addEventListener`
         // e aqui dentro tens acesso ao evento gerado, e a "param"

    }
}

#2 - criaObjeto receives parametro via .bind()

var criaObjeto = function(param, evento){
    // aqui dentro tens acesso a "param" e "evento" também

}.bind(null, parametro);
  • 1

    Thank you very much, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.