Scone Scone - 4 months ago 8
Ajax Question

Associate JSON array element with event handler

Is there a way, as I iterate through a JSON file to associate certain array elements with click handlers for a list?

What I have is this:

$.ajax(
{

url: 'json/data.json',
dataType : 'json',
type: 'get',
cache: false,
success: function(fullJSONData)
{
$(fullJSONData.events).each(function(index, oneJSONLine)
{
$('#eventList').append(newEvent(index, oneJSONLine))
$("#eventItem" + index).on("click", showEvent (fullJSONData.events[index]) );
});
},
error: function (e)
{
console.log("error " + e.message);
}

});


This is not working because all of the event handlers for showEvent() point to the last value that was in index. Can I get around this somehow?

Thanks

Answer

You are invoking the function, not passing it as reference.

Try

$(fullJSONData.events).each(function(index, oneJSONLine) {
    $('#eventList').append(newEvent(index, oneJSONLine))
    $("#eventItem" + index).on("click", function() {
        showEvent(fullJSONData.events[index]);
    });
});