knot22 knot22 - 4 months ago 8
Javascript Question

passing a value when using .on()

The addOnClickToPathContents() function is being used to add an onclick event to some dynamically created li tags such that when an li tag is clicked it calls the pathBuilder() function. The pathBuilder() function requires one argument. Is there a way to pass

fileList[f]
to pathBuilder as part of the .on() line of code? If so, how?



function addOnClickToPathContents(fileList)
{
for(var f in fileList)
{
$('#' + fileList[f]).on('click', pathBuilder);
}
}

function pathBuilder(file)
{
console.log(file);
//once this works, use file in logic within this function
}




Answer

There's two ways you can do this,

1) Bind the argument to the function:

function addOnClickToPathContents(fileList) {
  for(var f in fileList) {
    $('#' + fileList[f]).on('click', pathBuilder.bind(null, fileList[f]));
  }
}

function pathBuilder(file) {
  console.log(file);
}

2) Use an anonymous function to create a closure:

function addOnClickToPathContents(fileList) {
  for(var f in fileList) {
    $('#' + fileList[f]).on('click', function() {
      console.log(fileList[f]);
    })
  }
}