0

As my small project I am building a website where I need to dynamically add content based on the response from a server. Let's say I want to get the ports the server is currently listening on. The server returns a JSON array which looks like this:

[
    {"id": 0, "port": 80,  "active": true },
    {"id": 1, "port": 443, "active": false}
]

This array will be called ports later on.

Then for each port I'm making a table row with an edit button to change the port number or toggle it on/off. The event handler for the button receives a single port object as an argument like this:

function editPort(port) {
  //port is a single object from array, for example: {"port": 80, "active": true}
  //doSomething();
}

And I'm adding the event listeners in a simple loop like this:

for (port of ports) {
  //addRow();
  //addOtherCells();

  cell = document.createElement('td');
  cell.innerHTML = 'Edit port ' + port['port'];
  cell.addEventListener('click', () => {
    editPort(port);
  });

  //appendCellToRow(cell);
}

This obviously doesn't work because by the time loop finishes the port is the last array element and is passed to the handler regardless of which row is actually being clicked.

So my question is how to fix this to make the correct element to be passed to the handler instead of the last one?

Thank you!

EDIT: I'm using CoffeeScript which compiles the loop into this:

for (i = 0, len = ports.length; i < len; i++) {
  port = ports[i];
  ...
}
5
  • 1
    i think for(let port of ports) would work for you. Can you give it a try? Or second you can use data attribute to give id's to td's and then when u click one you can get the data attribute and find it on the array Commented May 24, 2020 at 17:30
  • let port of ports works in js, but I forgot to mention that I'm using coffeescript for the frontend which compiles the loop into this: for (i = 0, len = ports.length; i < len; i++) { port = ports[i]; } Commented May 24, 2020 at 17:38
  • 1
    Then it should be the other way so what you might wanna do is just use data attributes on <td>'s and gave the click action to the td's in general. Inside function you might just get data attribute and then use it to find it on array and change it? Commented May 24, 2020 at 17:40
  • That sounds like a good way to make it work Commented May 24, 2020 at 17:43
  • 1
    Yea give it a try. If you have problem just post your new code here so maybe we can help that =) Commented May 24, 2020 at 17:48

1 Answer 1

0

Turns out, there is a do keyword in CoffeeScript for this purpose which creates a function and runs it while passing the local variables into it (see this question for more info)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.