I have a couple of methods like receivedMessage, received... outside both the foreach loops in the code snippet below in JS. How do I bind the this keyword with both of them. I am using STRICT mode.
data.entry.forEach(function(pageEntry) {
let pageID = pageEntry.id;
let timeOfEvent = pageEntry.time;
// Iterate over each messaging event
pageEntry.messaging.forEach(function(messagingEvent) {
if (messagingEvent.optin) {
this.receivedAuthentication(messagingEvent);
} else if (messagingEvent.message) {
this.receivedMessage(messagingEvent);
} else if (messagingEvent.delivery) {
this.receivedDeliveryConfirmation(messagingEvent);
} else if (messagingEvent.postback) {
this.receivedPostback(messagingEvent);
} else if (messagingEvent.read) {
this.receivedMessageRead(messagingEvent);
} else if (messagingEvent.account_linking) {
this.receivedAccountLink(messagingEvent);
} else {
this.log("Webhook received unknown messagingEvent: ", messagingEvent);
}
}, this);
}, this);
I keep getting an error that says cannot call receivedMessage of undefined. I understand that the this keyword needs to be bound. How to do it in a nested foreach loop. I want the outer context bound to both foreach loops. Any suggestions?
[UPDATE 1] The code doesn't work. let me illustrate what I am trying to achieve and someone can probably help me out
I have a file with several functions in it. They call each other internally and I am using STRICT MODE. It would look something like this
'use strict';
module.exports = function(){
function call(){
small();
console.log('call');
}
function small(){
console.log('small');
}
}
I have another file , the main one that wants to supply a function from the first one as callback. Basically I want to do this
'use strict';
let messenger = require('./export-it.js');
console.log(messenger.call());
This should print 'small' and 'call' How to do this? Both internal function calls and this keyword binding is needed in strict mode.
UPDATE 2
This works perfectly but the code doesn't look clean :(
'use strict';
function call(){
small();
console.log('call');
}
function small(){
console.log('small');
}
module.exports.call = call;
module.exports.small = small;
There must be a way to group all those functions under one roof, No?