将其他参数传递给事件回调函数

时间:2019-03-19 00:32:30

标签: javascript callback arguments dom-events

我需要在事件上将其他参数传递给函数。

我尝试了bind,但它仅通过了e,而没有通过结果data

locationSearch.on("result", dropMarker.bind(this, e) );

我可以做到:

locationSearch.on("result", function(data) {
    dropMarker({ 
        e: e,
        data: data
    });
};

...但是由于无法监听器locationSearch.off(...)是匿名函数,因此无法禁用它。

2 个答案:

答案 0 :(得分:1)

只需将函数调用包装在另一个将成为回调的函数中

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>

答案 1 :(得分:0)

只需命名一个函数,然后调用它即可:

function handler(e) {
    dropMarker({ e: e, data: data });
}

locationSearch.on("result", handler);
相关问题