0

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?

PirateApp
  • 5,433
  • 4
  • 57
  • 90
  • instead of `, this` use `}.bind(this));` – Halfpint Aug 11 '16 at 02:44
  • thanks @Alex , you mean in both the loops? – PirateApp Aug 11 '16 at 02:47
  • Yes, change them both :) – Halfpint Aug 11 '16 at 02:47
  • :( thanks but i am still getting the same error 'Cannot read property 'receivedMessage' of undefined' – PirateApp Aug 11 '16 at 02:49
  • @Alex: isn't that forcing the same `this` as explicitly passing it to forEach? – dandavis Aug 11 '16 at 02:49
  • Could you dump your code into a pastebin? – Halfpint Aug 11 '16 at 02:49
  • i have added a single method called main in pastebin http://pastebin.com/SBBZgsnA let me know if you need more details. this is node.js – PirateApp Aug 11 '16 at 02:51
  • make sure you're passing the right thing as `this` by logging it before the loops – dandavis Aug 11 '16 at 02:52
  • @PirateApp: you can't bind the return, you would bind the callback itself, but that should do the same thing as the code above, so i suspect `this` is not what you think it is – dandavis Aug 11 '16 at 02:53
  • 1
    You're binding `this` wrong, instead of `}).bind(this);` it needs to be `}.bind(this));` – Halfpint Aug 11 '16 at 02:53
  • still getting the same error :( http://pastebin.com/Z5QUpmgE this is the new paste. the error says 'Cannot read property 'receivedMessage' of undefined' as usual – PirateApp Aug 11 '16 at 02:58
  • @PirateApp: so what does `this` look like when you log of outside the forEaches? – dandavis Aug 11 '16 at 03:00
  • OMG its undefined outside the both the foreach loops! – PirateApp Aug 11 '16 at 03:06
  • I think this is the issue http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal it seems I cannot use the this keyword inside an object literal. I have a literal var messenger = {main: ...} where the main and other functions are defined. I will try to achieve this with the ECMA 6 class construct – PirateApp Aug 11 '16 at 03:11
  • Have you read the accepted answer to that question? You CAN use it in an object literal. But read my answer to find out how "this" works. The problem is not in where the `this` is used but how the function is called. – slebetman Aug 11 '16 at 05:31
  • What object does `receivedAuthentication()` method belong to. Not only is the javascript interpreter confused as to what object it should find the method in, even I am confused. – slebetman Aug 11 '16 at 05:34
  • @slebetman, i just read your full answer, thanks :) a lot of points are clear now and since i am using strict mode , this is undefined. I broke the object into different functions added module.exports.a = fucn1..module.exports.b = func2 and so on. It works now though I haven't yet figured out the way for doing module.exports.a = obj where obj contains all the functions with this working properly inside it – PirateApp Aug 11 '16 at 05:37
  • @slebetman receivedAuthentication, receivedMessage and every other method you see are all part of the same object. What I am not sure about is if this works differently inside an object literal vs a class ECMA6 vs a function based constructor – PirateApp Aug 11 '16 at 05:39
  • Which object? `data`? `data.entry`? `pageEntry`? `pageEntry.messaging`? – slebetman Aug 11 '16 at 05:40
  • Ok here is a pastebin snippet of my code http://pastebin.com/1CRa3KZi Browse to the absolute bottom and you will see a function called main() and right inside this main, I am calling other methods that are defined above in the same paste. The functions are currently isolated or not placed inside any object and also the way i have exported it at the bottom is quite shabby. Some of these functions will be used as a callback method from a different file. What I am wondering is how to put all these functions inside an object and have the main() working properly to call the other internal methods – PirateApp Aug 11 '16 at 05:45

0 Answers0