-1

I'm freshman in javascript and try to understand more internal things.

I have some code on pure js. I build on page list of users what I got from JS array. And I try to make button delete user which gonna send list number where it pressed in callback function.

HTML

<div id="userTable"></div>

JS

var users = [
  {name: "Andrew"},
  {name: "Bob"},
  {name: "Ololo"}
];

function usersController(){
    usersView("userTable", users, {
        onDel: function(user){
            alert(user);
            //user.push({"name":"123"});
        }
    });
}

function usersView(selector, user, callback){
    ele = document.getElementById(selector);
    ele.innerHTML = "";
    var li, input;
    var ul = document.createElement('ul');
    for (x in user){
        li = document.createElement('li');
        input = document.createElement("input");
        input.type = "button";
        input.value = "Remove";
        //input.onclick = function(){alert(x);};
        input.addEventListener("click", function(){callback.onDel(x);});
        li.innerHTML = user[x].name;
        li.appendChild(input); 
        ul.appendChild(li);
    }
    ele.appendChild(ul);
}

Problems what I got whatever button I pressed get last number of list(2) all the time. Can I do that without jQuery and what's wrong with my code?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Krik99
  • 3
  • 3

1 Answers1

0

When the callback function is called, it takes the then-current value of x from the closure. Which will be 1. The simplest solution will be to replace this loop

    for (x in user){

with one using let (taking advantage of its block scope), like

for (let x of user) {
mbojko
  • 13,503
  • 1
  • 16
  • 26