If you attach event handlers via the onclick
HTML attribute, you can not control the parameters received by that handler. Let me quote the docs:
The single argument passed to the specified event handler function is a MouseEvent
object. Within the handler, this
will be the element upon which the event was triggered.
The way to pass a custom argument is to define a closure, by having a function that returns a function that receives only the event reference.
This is exactly the same solution as described in «Leaflet.contextmenu callbacks» and «Leaflet marker event fires at wrong time».
Read that. I mean it.
So in the end it should look something like:
function getHandlerForFeature(feat) { // A function...
return function(ev) { // ...that returns a function...
console.log(feat); // ...that has a closure over the value.
}
}
layer.bindPopup("<button id='mybutton'>Foo!</button>")
// The button doesn't exist in the DOM until the popup has been opened, so
layer.on('popupopen', function(){
L.DomEvent.on(
document.getElementById('mybutton'),
'click',
getHandlerForFeature(layer) // The result of this call is the event handler func.
);
});
Note that you can not use the onclick="code"
syntax, as you need to create a string of runnable code, and that code will only be able to access variables in the global scope. Sure, you can JSON.stringify()
your data, but you won't be able to have references to variables outside.