我需要将其他参数传递给事件上的函数。
我试过bind
,但它只通过e
而不是结果data
:
locationSearch.on("result", dropMarker.bind(this, e) );
我可以:
locationSearch.on("result", function(data) {
dropMarker({
e: e,
data: data
});
};
...但是我不能禁用监听器locationSearch.off(...)
,因为它是一个匿名函数。
只需将函数调用包装在另一个将成为回调的函数中
locationSearch.on("result", wrapper);
function wrapper(e) { dropMarker(e, data); }
这是一个例子:
$("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>
只需命名一个函数,然后调用它:
function handler(e) {
dropMarker({ e: e, data: data });
}
locationSearch.on("result", handler);