Maciej Kravchyk
Maciej Kravchyk

Reputation: 16607

Get the this context of the class in a bound method while preserving bound this

I'm creating a small helper class for addEventListener. The problem I run into is that I cannot effectively get both the this context of the class and the this context of the Event (the attached event target).

(1) If I use an arrow function, I can get the this of the class, but I cannot get the this which was bound (via Function.prototype.call)

(2) If I use a function expression, I can get the bound this, but I cannot access the class.

(3) I cannot use an inner closure either. The function/method has to be referenced from an outside scope.

This is a simplified example to show you what I mean. Is there a way to tick all boxes? All I could think of is to create another helper class which would be initialized for each event listener that is attached, but that does not seem very efficient if there is a simpler way.

class EventListenerHelper {
    private targets: Array<EventTarget>
    constructor() {
        // If there was a single target, it would be very easy. But there are multiple
        this.targets = [
            document.body,
            window
        ];
    }

     /**
     * (1) - Try to use an arrow function
     * 
     * This falls short because it's not possible to get the this context of the Event
     */
    private attachWithArrowFunction() {
        this.targets.forEach((target) => {
            target.addEventListener('click', this.listenerCallbackArrow, false);
        });
    }

    private listenerCallbackArrow = (e: Event) => {
        // Cannot get event this
        const eventThis = undefined; 

        // Note that e.target is the innermost element which got hit with the event
        // We are looking for that target that had the event listener attached
        // If I'm not mistaken, the only way to get it is from the this context
        // which is bound to the event callback

        this.processListener(eventThis, e);   
    }

    /**
     * (2) - Try to use a regular class method
     * 
     * This falls short because it's not possible to get the this context of the class
     */
    private attachWithClassMethod() {
        this.targets.forEach((target) => {
            target.addEventListener('click', this.listenerCallbackMethod, false);
        });
    }

    private listenerCallbackMethod(e: Event) {
         // Here we have the eventThis 
        const eventThis = this;

        // But the class instance is completely unreachable
    }

    /**
     * (3) - Try to create a closure wrapper
     * 
     * This almost works, but it's not possible to removeEventListener later
     */
    private attachWithClosure() {
        let self = this;

        this.targets.forEach((target) => {
            target.addEventListener('click', function(e: Event) {
                self.processListener(this as EventTarget, e);
            }, false);
        });
    }


    private processListener(eventThis: EventTarget, e: Event) {
        // Do some stuff with other class methods

        // 

    }

    private detach() {
        this.targets.forEach((target) => {
            target.addEventListener('click', this.listenerCallbackArrow, false);
        });
    }

}

Upvotes: 0

Views: 134

Answers (1)

jabuj
jabuj

Reputation: 3639

A common way to handle this is to return a function:

private attach() {
  const listener = this.getListener()
  this.targets.forEach(target => {
    target.addEventListener('click', listener, false)
  })
}

private getListener() {
  const self = this
  return function (e: Event) {
    // self if EventListenerHelper this
    // this is Event this
  }
}

But I don't see much benefit in it, because this inside a function that you pass to addEventListener is equal to event.currentTarget, so you could just bind your listener and use the property instead of this:

constructor() {
  // ...
  this.listener = this.listener.bind(this)
}
private listener(e) {
  // this is EventListenerHelper this
  // e.currentTarget is Event this
}

Upvotes: 2

Related Questions