Javascript onclick / addEventListener without anonymous function

1

I have a problem with the onclick / addEventListener of javascript, I have already tried it in several different ways and none has resulted, I wanted my click event to be equal to a function already declared and not equal to an anonymous function, but I do not I'm able to do this 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 would not really like to do something like this:

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

Because it breaks the idea of clean code, but none of the alternatives I tried worked, it just does not 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 rather as a normal function declared in the scope of the code.

The terminal does not trigger any errors at any time.

    
asked by anonymous 17.03.2017 / 03:39

1 answer

2

You have to create a function that returns another, or you do bind of that argument that 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);
    
17.03.2017 / 09:18