1

I have a function where I get some data, and insert it into a row of a table.

I then set up a click event on the row so that when it is clicked, it navigates to a URL specified in my data object:

$(data).each(function(i, item) {

    var row = $("<tr></tr>");
    tbody.append(row);

    // Add some cells into the row...
    var firstNameCol = $("<td>" + item.FirstName + "</td>");
    row.append(firstNameCol);

    // Set up click handler
    row.click(function() {
       window.location.href = item.DetailsURL;
    });
 });

Now this code works fine, but it has made me realise that I'm not sure how the events work.

The function contains a reference to item, which is a variable local to my for loop of items. When the user clicks on the row, how does it know which item it is looking at? Is it somehow cached when the click function is registered?

Secondly, is this method really bad? Am I forcing it to do a load of work behind the scenes?

0

1 Answer 1

2

item is a variable that's available in that scope when you bind, so that anonymous function you're passing into the .click() function just gets a copy of it (or reference if it's an object) at that time.

You could call this "cached", sure, but it's just a reference or a variable copy it gets at that point. .each() creates a closure, the callback function that you pass it (function(i, item) {...}), and inside there (depending on if it's an object or not, in that case you get the same reference) you get your own copy for that iteration of the loop.

As for performance, this isn't a "load of work" really, it's perfectly normal.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.