0

Im a java programmer trying to write javascript cant seem to grasp how scope changes when callbacks are called.

bot.sendmessage below failes to run. Error log says "undefined.bot.sendMessage(formId, resp)"

"use strict";

function Handlers() {
    this.bot = undefined;

    this.registerHandler = (bot)=>{
        this.bot = bot;
        bot.on('message', this._messageCallback);
        bot.on('inline_query', this._inlineCallback)
    }
}

Handlers.prototype = {

    _messageCallback: (msg) => {
        console.log("New Outline Request from: chat=" + msg.chat.id + ", uid=" + msg.from.id);
       
        var fromId = msg.from.id;
        var resp = "Hello there";
        this.bot.sendMessage(fromId, resp);
    },
    _inlineCallback: (msg) => {
        console.log("New Inline Request from: uid=" + msg.from.id);
        /*
         TODO::
         check if user is in data base if not log new entry;
         */
    }
};

module.exports = Handlers;

2
  • See Arrow functions. Commented Nov 11, 2016 at 12:56
  • that was the problem! thanks so much for your help:) add a answer and ill mark it as answered @teemu Commented Nov 11, 2016 at 16:30

1 Answer 1

1

First I need to say Teemu is correct. This is an issue with Arrow Functions which I myself am unfamiliar with. If you would like to see an alternative way of acomplishing the same thing without using Arrow Functions take a look at the snippet below.

This code I would change later to be an Immediately-Invoked Function Expression (IIFE) but that is my personal programming habits. I don't know your exact use case here.

"use strict";

/**
 * I'm assuming you have this elsewhere?
 * If not I have added it to show how to do it
 */
function bot(){
   /* ... */
}

bot.prototype = {
    sendMessage: function(formId,resp){
        console.log("Form: "+formId+" | Message: "+resp);
    }
};
/**
 * End of my addition
 */

function Handlers() {
    this.bot = new bot();
    
    /* ... */
}

Handlers.prototype = {

    _messageCallback: function(msg){
        /* ... */
        var fromId = "fakeid123";
        var resp = msg;
        this.bot.sendMessage(fromId, resp);
    },
    _inlineCallback: function(msg){
        /* ... */
    }
};

var myModule= new Handlers();
myModule._messageCallback("Here is my test msg.");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.