How to call global or external function into child function?

273 views Asked by At

I am using below code and when i am calling onMessageRender() function, so it says "this is not a function"

request = new Atmosphere.AtmosphereRequest(); // Global Function

Calling below code in ngONinIt

this.createSSE();

//Main function 
 createSSE(){ this.request.onMessage = function (response) {
        console.log('request.onMessage trigger');
         try {
           let jsonData = JSON.parse(message);
          console.log('Normal Message JSON this.request.util', jsonData);  
          this.onMessageRender();    
        }catch (e) {
           console.log('Error in websocket onmessage: ', e);
           return;
         } }

Created below function globally

onMessageRender(){

}

Please let me know if you need more information. Thanks!

2

There are 2 answers

7
kairun On

Assuming this is an Angular/typescript question,

if createSSE is declared as part of an Angular module, and if onMessageRender() is a global function which is not declared as part of an Angular module, calling onMessageRender() should be without this, as onMessageRender() may not be part of the same object that createSSE is declared.

If onMessageRender() is indeed part of the same object, I think more detail is required to answer your question.

0
Ambuj Khanna On

I would like to answer my own Question because after lots of fight. I got my working solution.

I need to convert my Normal/Old style function into Fat Arrow function because Arrow function always has this reference and it is available for that class object.

Old (Not Working)

this.request.onMessage = function (response) {...}

New (Working)

this.request.onMessage = (response) => {...}

After above changes, now it is accepting all other functions in it.

Thank you all for your time and support!