knot22
knot22

Reputation: 2768

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
}

Upvotes: 0

Views: 57

Answers (2)

Damon
Damon

Reputation: 4346

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]);
    });
  }
}

Edit: A more succinct approach that avoids jQuery id/class confusion.
Suppose you have a list:

<li class="file"></li>
<li class="file"></li>
<li class="file"></li>
...

You can iterate through these with jQuery:

$('.file').each(function(i, el) {
  $(el).click(pathBuilder.bind(null, fileList[i]));
});

Upvotes: 0

cstuncsik
cstuncsik

Reputation: 2796

Yes you can use event delegation on the parent element. Lets say you have the fileList object with all the data for the file. The keys are the IDs of the list elements and in this case you don't even need a loop, just pick one value from the object upon the list id on click. Keep it simple ;)

(function($){
  
  var fileList = {
    file1: {data: {url: '/file1'}},
    file2: {data: {url: '/file2'}},
    file3: {data: {url: '/file3'}},
    file4: {data: {url: '/file4'}}
  }
  
  var fileBuilder = function(file){
    console.log(file);
  }
  
  $(function(){
    
    $('#fileList').on('click', '.file', function(){
      var file = fileList[this.id];
      fileBuilder(file);
    });
    
    
    
  });
})(jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="fileList">
  <li class="file" id="file1">File 1</li>
  <li class="file" id="file2">File 2</li>
  <li class="file" id="file3">File 3</li>
  <li class="file" id="file4">File 4</li>
</ul>

Upvotes: 1

Related Questions