Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
A piece of JS code is needed to use multiple times with different values and function names. How to do it efficiently?

I have a script that is like this:

<div id="foo"></div>
<script>
var foo;
bar()
function bar() {
    var config = {
        a: "foo",
        b: "string",
        otherConfig1: ...
        otherConfig2: ...
        ...
    }
    
    foo = new NeoVis.default(config)
    foo.render();
    console.log(foo);
}
</script>

I want to have 8 more pieces of this, with different foo, bar and string. The otherConfigs are unchanged. I can simply duplicate them, but since the otherConfigs are very long, I would like to do this smarter. I have read about constructor, but since the function doesn't have any argument, I don't know how to apply this. I also try to move the config object outside of the function, but it seems that the code wouldn't run.

Neovis is a library. I also ask this on Neovis's Github: How to have multiple divs with different initial Cypher query?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could implement a function to which you pass the id, func, string as parameters to generate a function into the context you prefer (probably window). I have implemented a dummy NeoVis for the sake of the test, you will need to use yours instead.

var NeoVis = {
    default: function(config) {
        this.render = function() {};
    }
};

function myfunction(context, id, func, str) {
    context[id] = undefined;
    return context[func] = function() {
        var config = {
            a: id,
            b: str,
            //otherConfigs...
        };
        
        context[id] = new NeoVis.default(config);
        context[id].render();
        console.log(`function ${func} was called and ${id} is the id`);
    };
}

for (let item of document.querySelectorAll("#foo, #lorem, #dolor")) {
    myfunction(window, item.id, item.getAttribute("data-function"), item.innerText)();
}
<div id="foo" data-function="bar">string1</div>
<div id="lorem" data-function="ipsum">string2</div>
<div id="dolor" data-function="es">string3</div>

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda