1

My JavaScript code is as follows

$.getJSON( "sample_json.json", function( data ) {
  //javascript object
  var someId = data['item'][0]['id'];
  console.log("Outside addEventListener "+someId);

  //create <tr> element
  var tr = document.createElement('tr');

  //bind click event
  tr.addEventListener("click",function() {
    console.log("inside addEventListener "+someId);
    someFunction(someId);
  },false);       
});

//function
function someFunction(someId){
  console.log("Inside someFunction "+someId);
}

Now when I click on <tr> element it gives following in output

Outside addEventListener 150
Inside addEventListener 1
Inside someFunction 1

When I change someId as

var someId = 150;

It works perfectly

Outside addEventListener 150
Inside addEventListener 150
Inside someFunction 150

What should I change in javascript code to get the actual id from javascript object on click event ?

Note: I have already referred the existing question on Stack Overflow. How to pass arguments to addEventListener listener function? But have not helped much.

Edit: Updated javascript code with some jquery functions, which creates data javascript object from JSON file.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Pankaj
  • 360
  • 5
  • 22

2 Answers2

0

Perhaps you are changing someId later in the programme to 1 and that's why it the event handler prints 1 and not 150. If you create a closure around the event handler function you can bind the someId to the value it had at the time the event handler function was created (150). You can create a closure like this:

tr.addEventListener("click",(function(someId)
{
    return function() {
     console.log("inside addEventListener "+someId);
     someFunction(someId);
    }
})(someId),false);
0

Instead of passing object as argument, I would suggest you to use data-attribute

$.getJSON( "sample_json.json", function( data ) {
  //javascript object
  var someId = data['item'][0]['id'];
  console.log("Outside addEventListener "+someId);

  //create <tr> element
  var tr = document.createElement('tr');

  tr.setAttribute('data-someId', someId);

  //bind click event
  $('tr').on("click",function() {
    console.log("inside addEventListener "+$(this).data('someId'));
    someFunction($(this).data('someId'));
  },false);       
});

//function
function someFunction(someId){
  console.log("Inside someFunction "+someId);
}

Hope this will help you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38