0

NOTE: Originally titled "How do I allow a button "Click" handler to access variables defined by the code that creates the button?"

I have code that runs in a report web page for a COTS product via the jQuery.ready() function. My code has 2 parts: The "setup" code checks for a bunch of prerequisites and, if all conditions are good, it creates a button & adds a click handler for the button using AddEventListener. The second part is the click handler. In that I need most of the same variables that I defined in the "setup" portion. The quick and dirty way to do it is just copy the code from the "setup" but that seems inefficient and prone to error if I change something in the "setup" part and forget to replicate it in the "click handler".

Is there a way I can pass the variables I define in the "setup" section to an asynchronous event like a click handler?

// the click handler
const delAllSelected = () => {
   // In here I also need the "top_frame", "rpt_doc", "tbl_rptOutput" variables 
   //   defined in the "setup" portion.
   //  ... do stuff ...
}


// setup portion 
jQuery(document).ready(function () {
   var top_frame= top.window.document.querySelector("[name*=reportDialog]");
   var rpt_doc = top?.window?.frames[0]?.frames["List"]?.document;
   var tbl_rptOutput = rpt_doc.querySelector("#ReportOutput");
    ...etc...
   // if all the stars align, create a button and attach click handler
   if (all conditions good) {
       rpt_doc.querySelector("#CheckboxButtons td.btnFrame").insertAdjacentHTML("beforeend",`
       ... html for the "Delete All Selected" button goes here ...
       `);
       tbl_rptOutput.querySelector("#DeleteAllSelected").addEventListener("click",delAllSelected);
    }
}
mnemotronic
  • 856
  • 1
  • 9
  • 16
  • Define your `delAllSelected` function in the same scope as the variables, ie the _ready_ handler. Otherwise, pass them in as arguments – Phil Mar 03 '22 at 22:30
  • @Phil: Can you please expand on "pass them in as arguments"? I don't understand the context. Thx in advance. – mnemotronic Mar 03 '22 at 23:09
  • `const defAllSelected = (top_frame, rpt_doc, tbl_rptOutput) => { ... }`. See the post linked at the top of your question for more details – Phil Mar 03 '22 at 23:10

0 Answers0