Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda