1

Calling the LWC Javascript function from the subscribe() method of CometD results in function undefined.

Here is the code:

<code>

import { LightningElement, api, track, wire } from 'lwc'; import getMessageRecords from "@salesforce/apex/PCMMessageController.fetchMessageRecordsComUser"; import insertMessage from "@salesforce/apex/PCMMessageController.insertMessageComUser"; import updateReadInMsgRecord from "@salesforce/apex/PCMMessageController.updateReadInMsgRecForComUser"; import getUserDetails from "@salesforce/apex/PCMMessageController.getUserDetails"; import cometdlwc from "@salesforce/resourceUrl/cometd"; import { loadScript } from "lightning/platformResourceLoader"; import getSessionId from '@salesforce/apex/SessionUtil.getSessionId'; import welcomeToChat from '@salesforce/label/c.Welcome_to_Chat'; import messageSentTime from '@salesforce/label/c.Message_Sent_Time'; import messageSender from '@salesforce/label/c.Message_Sender';

export default class CustomMessage extends LightningElement {

@api flexipageRegionWidth = 'CLASSIC'; 
@track messageRecords;
@track inputMessage = '';
libInitialized = false;
@track sessionId;
@track showWelcomeMsg=false;
@track loggedInUserWrapper;
welcomeToChat=welcomeToChat;
messageSentTime=messageSentTime;
messageSender=messageSender;

@wire(getSessionId)
    wiredSessionId({ error, data }) {
    if (data) {
        console.log(data);
        this.sessionId = data;
        this.error = undefined;
        loadScript(this, cometdlwc)
        .then(() => {
                                    console.log('######In SessionmessageRecords:'+this.messageRecords);
                this.initializecometd()
        });
    } else if (error) {
            console.log(error);
            this.error = error;
            this.sessionId = undefined;
        }
}

initializecometd() {
    if (this.libInitialized) {
        return;
    }
    this.libInitialized = true;
    //inintializing cometD object/class
    var cometdlib = new window.org.cometd.CometD();
    //Calling configure method of cometD class, to setup authentication which will be used in handshaking
    cometdlib.configure({
        url: window.location.protocol + '//' + window.location.hostname + '/cometd/47.0/',
        requestHeaders: { Authorization: 'OAuth ' + this.sessionId},
        appendMessageTypeToURL : false,
        logLevel: 'debug'
    });
    console.log('#####SessionID:'+this.sessionId);
    cometdlib.websocketEnabled = false;

    cometdlib.handshake(function(status) {
        if(status.successful) {
            // Successfully connected to the server.
            // Now it is possible to subscribe or send messages
            console.log('#####Successfully connected to server');
            // Callback invoked whenever a new event message is received
            /*const messageCallback = (response) => {
                console.log('#####Platform Event received : ', JSON.stringify(response,null,' '));     
            };*/
             /*  cometdlib.subscribe('/event/PCM_Chat_Internal_COMM__e',function(msg) {
                console.log("this.messageRecords:::"+this.messageRecords);
               });*/
                            /*cometdlib.subscribe('/event/PCM_Chat_Internal_COMM__e', (msg) => {
                                    console.log("this.Event msg:::"+JSON.stringify(msg));
                                    console.log("this.messageRecords:::"+this.messageRecords);
                                    this.invokeLWCApexMethod();
                            });*/
                            let self = this;
                            cometdlib.subscribe('/event/PCM_Chat_Internal_COMM__e',function(msg) {
                                    console.log("this.Event msg:::"+JSON.stringify(msg));
                                    self.invokeLWCApexMethod();
                            });
        } else {
            /// Cannot handshake with the server, alert user.
            console.error("#####Error in handshaking:" + JSON.stringify(status));
        }
    });
}
    invokeLWCApexMethod(){
        //Calling Apex Method
    console.log('#####Calling Apex Method');
    }
checkForNewMessages=function(perAccRecId) {
    console.log("checkForNewMessages^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
    /*for(var msg=0;msg<this.messageRecords.length;msg++) {
        if(perAccRecId===this.messageRecords[msg].Person__c) {
            toRefreshMessages=true;
            break;
        }
    }
    if(toRefreshMessages) {
        //get the latest messages from Apex.
        console.log("********************Same Person Account***********************");
        this.invokeApexForMessageRecords();
    } else {
        console.log("********************Different Person Account***********************");
    }*/
}

connectedCallback() {  
    this.invokeApexForMessageRecords();
}

invokeApexForMessageRecords() {
    getMessageRecords()
        .then(result => {
            this.messageRecords = result;
            if(this.messageRecords.length==0) {
                this.getLoggedInUserDetails();
            }
        })
        .catch(error => {
            console.error("error:"+JSON.stringify(error));
        });
}

getLoggedInUserDetails() {
    getUserDetails()
        .then(result => {
            this.loggedInUserWrapper = result;
            this.showWelcomeMsg = true;
        })
        .catch(error => {
            console.error("error:"+JSON.stringify(error));
        });
}

handleMessageChange(event) {        
    this.inputMessage = event.target.value;     
}

sendChatMessage() {
    if(this.inputMessage) {
        insertMessage({ newMessage: this.inputMessage})
        .then(result => {
            this.messageRecords = result; 
            this.inputMessage = "";      
        })
        .catch(error => {
            console.error("error:"+JSON.stringify(error));
            this.inputMessage = "";
        });
    }
}

checkSendChatMsgOnEnter(event) {
    if(event.keyCode==13) {
        this.sendChatMessage();
    }
}

updateReadInMessage(event) {
    var msgId = event.target.dataset.messageid;
    updateReadInMsgRecord({ messageId: msgId }) 
    .then(result => {
        this.messageRecords = result; 
    })
    .catch(error => {
        console.error("error:"+JSON.stringify(error));
    });
}

}

1
  • Please update the question not an answer Jan 26, 2021 at 16:13

1 Answer 1

3

As you are using an anonymous function, it will not have access to the this of your component. A this inside that function will refer to the function itself.

To overcome this, you have two options.

1 Use an arrow function

cometdlib.subscribe('/event/MSG_Internal_COMM__e', (msg) => {
    this.invokeLWCApexMethod();
});

2 Pass this as another variable i.e. self

// ...
let self = this;
cometdlib.subscribe('/event/MSG_Internal_COMM__e',function(msg) {
    self.invokeLWCApexMethod();
});

Change that to an arrow function like below as this remains unchanged in arrow functions.

10
  • Thanks RAHUL for your reply. I have tried with both formats using arrow but they didn't work. I got the same error. Exception during execution of listener {id: 1, channel: "/event/PCM_Chat_Internal_COMM__e", scope: undefined, listener: false, callback: ƒ} {data: {…}, channel: "/event/PCM_Chat_Internal_COMM__e"} TypeError: s.invokeLWCApexMethod is not a function
    – user92261
    Jan 26, 2021 at 15:43
  • @user92261 you need to do the same for outer function, here cometdlib.handshake(function(status) { Jan 26, 2021 at 15:53
  • not sure whether i'm doing it rightly. I 'have posted my sample code at easyupload.io/br3b16
    – user92261
    Jan 26, 2021 at 16:06
  • @user92261 can you update the relevant code snippet in the original question. Jan 26, 2021 at 16:10
  • the relevant code added.
    – user92261
    Jan 26, 2021 at 16:13

You must log in to answer this question.

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