I do have an initializing allocative function with hooks to optional call other functions. The Idea is, that the (other) functions could be written individual to the project to add individual needed features.
The mechanic works fine if there is only one call on a page.
Now I would like to realize multiple use of that function on one page. That means on every call the allocative function should call hooks with different and individual code for every single call. That means: after I called function and hooks the first time I have to change the code of the hooks for the second call.
Up to now I 'reset' the hook functions before starting the second call and coding the hooks new.
The question is about: is there a way to write better, a more easier and maybe more elegant code?
I would prefer a mechanic without the 'reset' but starting directly with coding the hooks for the second call. Is that possible maybe with using another scope for the variables? The solution should be realized without use of classes and in vanilla Javascript (no jQuery).
Here is the simplified(!) code to demonstrate the mechanic:
<h1 id="hd1" class="heading main normal">Testing JS</h1>
<h2 id="hd2" class="subheading article">Another headline</h2>
<script type="text/javascript">
let hookBeforeStart,hookAfterDone; // initializing vars for hooks
function resetHookFuncions(){
hookBeforeStart = {};
hookAfterDone = {};
}
function allocativeFunction( selector ){
const $element = document.getElementById( selector );
const classes = $element.classList;
const eHtml = $element.innerHTML;
// hooks
if(typeof(hookBeforeStart) == 'function'){
hookBeforeStart({ $element, classes });
}
if(typeof(hookAfterDone) == 'function'){
hookAfterDone({ $element, eHtml });
}
}
window.onload = function(){
// ### first call allocative function with individual hooks
console.log('first call');
hookBeforeStart = function( p ){
console.log( p.classes );
};
hookAfterDone = function( p ){
console.log( p.eHtml );
}
allocativeFunction('hd2');
// ### second call allocative function with same hooks but other individual code
console.log('second call');
//###### RESET
//###### SEEMS TO BE LESS ELEGANT AND COMPLICATED
//###### IS THERE A BETTER WAY WITHOUT RESET????
resetHookFuncions();
// note: hookBeforeStart not needed for second call
// --> has been (needed to be) deleted by reset
hookAfterDone = function( p ){
console.log( p.$element );
}
allocativeFunction('hd1');
} // window.onload
</script>
All hints and suggestions to do it better are welcome.
question from:
https://stackoverflow.com/questions/65928055/javascript-code-optimizing-multiple-use-of-allocative-function-with-variable-ho 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…