medihack
medihack

Reputation: 16627

Reference bound function inside itself in strict mode

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!

Upvotes: 2

Views: 65

Answers (2)

JJWesterkamp
JJWesterkamp

Reputation: 7916

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.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138427

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

function foo () {
  function callback (){
    //...
    eventBus.removeListener(callback);
  }
  eventBus.addListener(callback);
}

Upvotes: 1

Related Questions