2

I need to have a bound event listener function to reference itself, but I don't see a way to access itself in strict mode (arguments.callee is not available).

See the following code snippet for an example:

function callback(boundParam, event) {
  // This does not work here as not 'callback' was added
  // to the event bus but 'boundCallback'
  eventBus.removeListener(callback);   
}

function foo () {
  const boundCallback = callback.bind({}, 7);
  eventButs.addListener(boundCallback);
}

What are my options?

This is NOT a duplicate of JavaScript: remove event listener as I need to reference a bound function!

medihack
  • 16,045
  • 21
  • 90
  • 134
  • @mike not really. None of the top answers would work here – Jonas Wilms Mar 23 '18 at 20:40
  • Not a duplicate - this is an eventing system rather than a simple event. – Randy Casburn Mar 23 '18 at 20:40
  • `bind` creates a copy of the function to bind, and the copy has its own reference. You need to keep track of the bound listeners, so that you can get a reference to the copy at the time you want to remove an event listener. – Teemu Mar 23 '18 at 20:49

2 Answers2

1

Maybe inline the handler so that you dont need to bind:

function foo () {
  function callback (){
    //...
    eventBus.removeListener(callback);
  }
  eventBus.addListener(callback);
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

You could create a function that returns a reference to the bound function when called. Let's call that function getBoundCallback. Then, append it to the argument list of the bind() call in order to receive the function in callback. You should then be able to call getBoundCallback and get back the actual bound function:

function callback(boundParam, getBoundCallback, event) {
    eventBus.removeListener(getBoundCallback());
}

function foo() {
    let boundCallback;
    const getBoundCallback = () => boundCallback;
    boundCallback = callback.bind({}, 7, getBoundCallback);
    eventButs.addListener(boundCallback);
}

Note how the declaration and initialisation of boundCallback are separated because of the reference to getBoundCallback being required for the statement initialising boundCallback.

JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28