Search code examples
javascriptarrayselectrondom-eventsuuid

Unique ID with a specific variable to call a function in an array using said variable


I apologize in advance if this is a stupid question am new to JavaScript and Electron.js.

In this example, I have Btn1, Btn2, Btn3 and each button is linked to a specific variable.
An onclick event listener for each button all connect to the same function and or array.
Depending on the button which was clicked, it will run that function using the variable linked to the button that was pressed.

let buttons = [btn1, btn2, btn3]
   
let open = document.getElementById('Btn1')
open.addEventListener('click', (event) =>{
   let btn1_value = 1
   //2 more of these for each button
})
}

I am not just having a set of preset functions or a series of if-case statements.
As I am trying to dynamically allow a user to add buttons to my software with using the same function.
However, using different data (files in this case) stored in a array.

I have decided to try a method like this due to my current knowledge.
It is more manageable (for me) to add and remove data from an array, using push() and pop().
Than having to create multiple functions for each button created, especially dynamically.

Any help or direction is greatly appreciated.


Solution

  • I think i get your point, something like that: https://jsfiddle.net/ve209L7j/2/

    // File Groups, global scope
    var files = {
        'group_1': [
        'file1.pdf',
        'file2.pdf',
        'file5.pdf',
      ],
        'group_2': [
        'file3.pdf',
        'file4.pdf',
        'file5.pdf',
      ],
        'group_3': [
        'file1.pdf',
        'file2.pdf',
        'file3.pdf',
        'file4.pdf',
        'file5.pdf',
      ],
    };
    
    // btns to create
    var btns = [
        {
        id: 'btn1',
        label: 'Files1',
        custom: 'group_1'
      },
        {
        id: 'btn2',
        label: 'Files2',
        custom: 'group_2'
      },
        {
        id: 'btn3',
        label: 'Files3',
        custom: 'group_3'
      },
    ];
    
    // create btns dynamic
    function createButton(btn, listener) {
      const el = document.createElement('button');
      el.setAttribute('id', btn.id)
      el.setAttribute('data-custom', btn.custom);
      el.textContent = btn.label;
      el.addEventListener('click', listener);
      document.body.appendChild(el);
      return el;
    }
    
    // your callback listener
    function btnCallback(event) {
      var custom = event.currentTarget.dataset.custom;
      console.log('files:', files[custom]);
    }
    
    // create buttons
    btns.forEach(function(btn) {
      var buttonCreated = createButton(btn, btnCallback);
      // @TODO - something usefful with btn El if you need [buttonCreated]
    });
    
    

    OLD AWSNER, BEFORE AUTHOR RESPONSE:

    What I understand is that you want to use the same callback function, but each button has a different context / argument.

    Either way, it also abstracts the listener bind. https://jsfiddle.net/ve209L7j/

    Javascript:

    var files = {};
    
    function binder(ids, callback) {
      ids.forEach(function(id) {
        var btn = document.getElementById(id);
        btn.addEventListener('click', callback);
      });
    }
    
    function functionWithButtonContext(event) {
      var custom = event.currentTarget.dataset.custom;
      console.log('custom:', custom);
    }
    
    binder(['Button1', 'Button2', 'Button3'], functionWithButtonContext);
       
    

    HTML - I used the attribute "data"

    <button id="Button1" data-custom="btn1">
      Button 1
    </button>
    <button id="Button2" data-custom="btn2">
      Button 2
    </button>
    <button id="Button3" data-custom="btn3">
      Button 3
    </button>