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

Viewed 116

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.

3 Answers

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>

If you need to have a dynamic array for buttons config and use some static listener function you can write something like this. Here you can update the array with any count of buttons(in my example button is required to have id and title) and they all will be added to DOM

<script>
  var btns = [
      {
        id:'bnt1',
        title: 'btn1'
      },
      {
        id:'bnt2',
        title: 'btn2'
      },
      {
        id:'bnt2',
        title: 'btn2'
      }
  ];

  function listener(event) {
    alert('Button - ' + event.target.id + ' has been clicked');

  }
  btns.forEach((btn) => {
      const el = document.createElement('button');
      el.setAttribute('id', btn.id)
      el.textContent = btn.title;
      el.addEventListener('click', listener);
      document.body.appendChild(el);
  });
</script>
let buttons = [btn1, btn2, btn3]
for(let i in buttons){
  document.getElementById(`Btn${i+1}`)
  .addEventListener(event)=>{
    //buttons[i] would be the unique number for each different button click listener
  }
}

In a working demonstration..

let buttons = [0, 0, 0]
let p=document.getElementById('buttons')
p.innerText=buttons
for(let i in buttons){
  i=parseInt(i)
  document.getElementById(`Btn${i+1}`)
  .addEventListener('click',(event)=>{
    buttons[i]++
    p.innerText=buttons
  })
}
<button id="Btn1">Button 1</button>
<button id="Btn2">Button 2</button>
<button id="Btn3">Button 3</button>
<p id="buttons"></p>

Related