0

I'm trying to add popups to omnivore layers in Leaflet. I'm going to have a lot of these layers, so I want to write a function to add the same style and popup to each layer. Each of the layers needs to have its own popup text. I wrote the function, but when I try to run the code, I get "Uncaught TypeError: undefined is not a function".

This code won't work:

function stylize(place) {
  this.setStyle({
    color: '#f00',
    opacity: 1
  });
  this.bindPopup(place);
  this.addTo(mapLayer);
};

omnivore.gpx('place-a.gpx')
.on('ready', stylize('Place A'));

And this won't work:

omnivore.gpx('place-a.gpx')
.on('ready', function() {stylize('Place A');});

While this will:

function stylize() {
  this.setStyle({
    color: '#f00',
    opacity: 1
  });
  this.bindPopup('Place A');
  this.addTo(mapLayer);
};

omnivore.gpx('place-a.gpx')
.on('ready', stylize);

Why am I not able to add arguments to this function?

user2926101
  • 314
  • 1
  • 3
  • 13
  • 1
    Whenever you have something of the form `foo(bar())`, `bar` is executed first and its return value is passed to `foo`. So in your case, instead of passing a reference to `stylize` to `.on()`, you are executing `stylize` and pass its return value to `.on()` (which is not a function). – Felix Kling Jun 01 '14 at 18:44
  • I should have mentioned that I already tried .on('ready', function() {stylize('Place A');}); which seems to be what your duplicate question suggests. That isn't working either. – user2926101 Jun 01 '14 at 18:50
  • True, reopened and answered. – Felix Kling Jun 01 '14 at 19:46

1 Answers1

2

How to pass arguments to callbacks in general is covered in Javascript: how to pass parameters to callback function .

However, you also relying on this referring to a specific object. So you have to set this explicitly, using .call:

omnivore.gpx('place-a.gpx').on('ready', function() {
  stylize.call(this, 'Place A');
});

To learn more about this, have a look at the MDN documentation.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143