将数据对象传递给触发事件
Passing data object to fire event
我正在使用 Mapbox GL,文档指出:
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.
来源:https://www.mapbox.com/mapbox-gl-js/api/#evented#on
所以如果我这样做:
map.on('click', 'somelayer', { customData: 'foo' }, customFunction);
我收到一个错误:
Uncaught TypeError: i.call is not a function
我做错了什么?
您需要删除 {customData: 'foo'}
:
map.on('click', 'somelayer', customFunction);
mapbox-gl 尝试将您的对象作为函数执行。
您可以使用绑定:
map.on('click', customFunction.bind({customData: 'foo'}))
或者如果你想保存上下文,你可以使用包装器:
function extend(fn, data) {
return (e) => {
e.data = data
fn(e)
}
}
map.on('click', extend(customFunction, {
customData: 'foo'
}))
我正在使用 Mapbox GL,文档指出:
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.
来源:https://www.mapbox.com/mapbox-gl-js/api/#evented#on
所以如果我这样做:
map.on('click', 'somelayer', { customData: 'foo' }, customFunction);
我收到一个错误:
Uncaught TypeError: i.call is not a function
我做错了什么?
您需要删除 {customData: 'foo'}
:
map.on('click', 'somelayer', customFunction);
mapbox-gl 尝试将您的对象作为函数执行。
您可以使用绑定:
map.on('click', customFunction.bind({customData: 'foo'}))
或者如果你想保存上下文,你可以使用包装器:
function extend(fn, data) {
return (e) => {
e.data = data
fn(e)
}
}
map.on('click', extend(customFunction, {
customData: 'foo'
}))