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.
this
context. You can try using the arrow functionconst messageCallback = (response) => { //Your code here }
to preserve originalthis
context.