1

I need to update a global variable when a push topic is created.

import { LightningElement, track,api } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';

export default class ContactChangeNotifiier extends LightningElement {
    channelName = '/topic/PushTopicName';
    @track response;
    subscription = {};
    @track showComponent = false;

     // Initializes the component
    connectedCallback() {  
        this.showComponent = false;   
         this.handleSubscribe();  
    }
    // Handles subscribe button click
    handleSubscribe() {   
        const messageCallback = function(response) {
            console.log('global variable is : ',this.showComponent);
            console.log('New message received: ', response);          
        };             
        subscribe(this.channelName, -1, messageCallback).then(response => {            
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
            console.log('this.subscription ', +this.subscription);
        });
    }
}

I'm trying to access "showComponent" variable in "messageCallback" method. But, I'm getting undefined in console messages.

enter image description here

1
  • 1
    Using a function like that creates it's own this context. You can try using the arrow function const messageCallback = (response) => { //Your code here } to preserve original this context.
    – manjit5190
    Commented Aug 8, 2020 at 20:23

1 Answer 1

1

You can bind to this:

subscribe(this.channelName, -1, messageCallback.bind(this)).then(response => {
  ...

Or, you can use an arrow function:

const messageCallback = (response) => {
    ...

Either way would preserve the correct scope for you.

2
  • subscribe(this.channelName, -1, messageCallback.bind(this)) - it worked.
    – Manoj
    Commented Aug 9, 2020 at 5:49
  • const messageCallback = (response) => {} - This is also worked.
    – Manoj
    Commented Aug 9, 2020 at 5:57

You must log in to answer this question.

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