2

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:

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.

0

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Yea, but the library doesn't provide a one or once emitter so I also need to turn off the listener immediately which isn't possible with an anonymous function, right?
But again, you can't disable the listener as stated in the question since it's an anonymous function.
I've updated the answer. With a named function, you can remove the handler.
0

Just name a function and then call it:

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

locationSearch.on("result", handler);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.