Home > front end >  how do i use a changeable value in a function parameter?
how do i use a changeable value in a function parameter?

Time:04-04

it's pretty hard to explain, but I know why what I tried doesn't work I just want to know if there is a solution. I hope you can understand what I want to do through the code

async function copyInvite() {
    let buttons = document.querySelectorAll("button.rl-btn-invite");

    addEventListenerLoop(buttons, 'click', event => { navigator.clipboard.writeText(node.id); });
}



async function addEventListenerLoop(nodes, type, code) {
    for (const node of nodes) {
        node.addEventListener(type, code);
    }
}

I am trying to make a value in the function change based on what node I am doing it on

I tried using mutable values but it either didn't work or I didn't try well enough.

CodePudding user response:

If I understand you right, you are looking for a solution to have access to the current node in your code callback.

For this, you can try to nest your callback methods, where the outer one receives the current node and returns the actual event handler for this specific node.

This will look like this:

async function copyInvite() {
    let buttons = document.querySelectorAll("button.rl-btn-invite");

    addEventListenerLoop(buttons, 'click', node => event => { navigator.clipboard.writeText(node.id); });
}


async function addEventListenerLoop(nodes, type, code) {
    for (const node of nodes) {
        node.addEventListener(type, code(node));
    }
}

CodePudding user response:

Given your example, the simplest solution would be to use event.currentTarget instead of node to refer to the element the handler was bound to:

addEventListenerLoop(
  buttons,
  'click',
  event => { navigator.clipboard.writeText(event.currentTarget.id); }
  //                                       ^^^^^^^^^^^^^^^^^^^
);

CodePudding user response:

The reason it doesn't work is because the buttons variable is of type NodeList. Actually, your build is pretty cool. You just need to send nodes as [...buttons] when running the addEventListenerLoop function.

Description of this code; You cannot traverse the nodeList with forEach, for-in for-of loops. This is because forEach vs. functions belong to Array.prototype, and Array and NodeList are different. Thanks to the spread operator, we actually convert a NodeList to Array. In this way, now for-in for-of etc. We can use Array.prototype functions!

async function copyInvite() {
let buttons = document.querySelectorAll("button.rl-btn-invite");

addEventListenerLoop([...buttons], 'click', event => { 
navigator.clipboard.writeText(node.id); });
}
  • Related