[英]Passing additional arguments to an event callback function
I need to pass additional arguments to a function on an event.我需要将额外的参数传递给事件的函数。
I tried bind
but it only passes the e
and not the result data
:我试过
bind
但它只通过e
而不是结果data
:
locationSearch.on("result", dropMarker.bind(this, e) );
I could do:我可以:
locationSearch.on("result", function(data) {
dropMarker({
e: e,
data: data
});
};
... but then I can't disable the listener locationSearch.off(...)
since it is an anonymous function. ...但是我无法禁用侦听器
locationSearch.off(...)
因为它是一个匿名函数。
Just wrap the function call in another function that will become the callback只需将函数调用包装在另一个将成为回调的函数中
locationSearch.on("result", wrapper);
function wrapper(e) { dropMarker(e, data); }
Here's an example:下面是一个例子:
$("button").on("click", wrapper); let data = "some data"; function wrapper(e){ // The wrapper just calls the actual handler handler(e, data); } function handler(e, data){ // Because the wrapper was named, it can be disconnected $(e.target).off("click", wrapper); // And you can do whatever you need to console.log(e.type, data); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click Me</button>
Just name a function and then call it:只需命名一个函数,然后调用它:
function handler(e) {
dropMarker({ e: e, data: data });
}
locationSearch.on("result", handler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.