0

I have a component that picks up the value originally from the JS controller but won't refresh after I modify the value in the JS file.

Component:

<template>
    <div class={outterWrapperClass}/>
</template>

JS:

import { LightningElement, track } from 'lwc';

export default class SomeClass extends LightningElement {
    @track outterWrapperClass = 'outter-wrapper';

    connectedCallback() {
        window.addEventListener('scroll', function() {
            if (window.pageYOffset < 260) {
                this.outterWrapperClass = 'outter-wrapper';
            } else {
                this.outterWrapperClass = 'outter-wrapper-sidebar';
            }
            console.log('outer is ' + this.outterWrapperClass);
        });
    }
}

The value for this.outterWrapperClass is changing correctly in the console but the component's class value won't refresh. It's stuck on outter-wrapper. What am I doing wrong?

2 Answers 2

1

In the general sense, you'll want to have a separate function and bind that reference to the event handler:

connectedCallback() {
    window.addEventListener('scroll', this.scrollHandler.bind(this));
}
scrollHandler() {
    if (window.pageYOffset < 260) {
        this.outterWrapperClass = 'outter-wrapper';
    } else {
        this.outterWrapperClass = 'outter-wrapper-sidebar';
    }
    console.log('outer is ' + this.outterWrapperClass);
}

Function.prototype.bind will ensure that this refers to the component and not the window.

1
  • Thanks for providing some additional input.
    – Arthlete
    Aug 2, 2019 at 18:51
0

I got the answer from here.

In case that link disappears for whatever reason - The answer to this question is because I was using a regular function declaration so "this" was not what I was hoping to be. I had to switch to a fat arrow function and things worked out.

You must log in to answer this question.

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