0

I am trying to create a button listener function inside bindPop in leaflet. But it does not read parameter of onclick function. In the below code alertConfirmed()function works fine for me but filterEventsBasedOnCluster(feature) does not read the parameter 'feature'. It says feature is not defined. feature is an object.

here is the code:

 layer.bindPopup('<div id="alert">Found...!<input type="button" value="Please confirm" onclick="alertConfirmed()"> <input type="button" id="create" value="see patients" onclick="filterEventsBasedOnCluster(feature)"><table id="table"></table></div>')

`

Any help is much appreciated.

Prashanth Benny
  • 1,523
  • 21
  • 33
  • Currently you are sending your parameter feature as a 'feature' object. You should be sending it like +feature+ if you have defined feature as a variable object in your program. – Prashanth Benny Feb 10 '17 at 11:02

2 Answers2

0

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.

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
-1

try this:

I am just correcting the wrong part only:

onclick="filterEventsBasedOnCluster('+feature+')"

You are not passing the variable properly.

Dirty Developer
  • 551
  • 5
  • 22