4

I want to ad an eventListener for window resize inside my custom lightning web component but I don't know how to do it

Maybe something like this?

constructor(){
    window.addEventListener('resize', this.handleResize());
}
handleResize(){
    //custom code
}

2 Answers 2

7

you need to pass the function by reference and not invoke it directly while declaration. Later it will be invoked when the event is triggered. PFB:

connectedCallback() {
    window.addEventListener('resize', this.myFunction);
}
@track count = 0;
myFunction = () => {
    this.count = this.count += 1;
    console.log('resized => ', this.count);
};

Here is the playground link

2
  • How long do you think the window support would be there for LWC?
    – Arthlete
    Commented May 16, 2020 at 3:01
  • 1
    @Arthlete, I think it will be always supported. Salesforce documentation uses window here. Also locker apis shows it available. Also Lwc is meant to be close to normal web development as close as possible. If they limit so many things, lwc will follow aura (sometime extinct) Commented May 16, 2020 at 6:15
7

If you want to access 'this' in the event handler, you need to:

window.addEventListener("resize", this.myFunction.bind(this))
2
  • Thank you! This is the key for getting this.template to exist in the resize handler.
    – mhenry1384
    Commented Dec 27, 2021 at 18:16
  • 2
    You don't need to bind if you do it using arrow functions as @salesforce-sas has done Commented Mar 22, 2022 at 0:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .