Leaflet marker event fires at wrong time

You’re confusing the concepts of function references and function calls, and you are not making a closure over the item ID.

If you declare this:

function onItemClick(id) { alert(id); }

This prints the reference to the function:

console.log( onItemClick );

And this prints the return value of calling that function (as it returns nothing, this equals undefined):

console.log( onItemClick(5) );

So when you’re doing this:

L.marker(....).on('click', onItemClick(id) );

the function gets called, and on() receives the return value of that function, i.e.:

L.marker(....).on('click', undefined );

What you want to do is have a function that returns a function:

function onItemClick(id) { return function(){ alert(id); } }

This way, when you do

L.marker(....).on('click', onItemClick(5) );

That will make a function call, and use the return value, which now looks like this:

L.marker(....).on('click', function() { alert(5); } );

Leave a Comment