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];
...
}
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 arraylet port of portsworks 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]; }