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?
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>