1

I'm using Mapbox GL and the doc states:

Adds a listener to a specified event type.

Parameters:

type(string) The event type to add a listen for.

listener(Function) The function to be called when the event is fired. The listener function is called with the data object passed to fire , extended with target and type properties.

Source: https://www.mapbox.com/mapbox-gl-js/api/#evented#on

So if I do:

map.on('click', 'somelayer', { customData: 'foo' }, customFunction);

I get an error:

Uncaught TypeError: i.call is not a function

What am I doing wrong?

eozzy
  • 66,048
  • 104
  • 272
  • 428

2 Answers2

3

You can use the bind:

map.on('click', customFunction.bind({customData: 'foo'}))

Or if you want to save the context, you can use a wrapper:

function extend(fn, data) {
  return (e) => {
    e.data = data
    fn(e)
  }
}
map.on('click', extend(customFunction, {
  customData: 'foo'
}))

[ http://jsfiddle.net/tu570Lgz/ ]

stdob--
  • 28,222
  • 5
  • 58
  • 73
  • What about if we use arrow functions? See http://jsfiddle.net/oy8j9L75/ customData isn't passed to customfunction. – Toni BCN Apr 30 '21 at 08:13
  • @ToniBCN You cannot rebind this in an arrow function - https://stackoverflow.com/a/33308151/4989460 – stdob-- Apr 30 '21 at 11:22
-2

You need to drop the {customData: 'foo'}:

map.on('click', 'somelayer', customFunction);

mapbox-gl tries to execute your object as a function.

Scarysize
  • 4,131
  • 25
  • 37