Search code examples
javascripttypescriptbotframeworkthisthis-pointer

When running a validation through the bot framework how can I assure properties are mutable that belong to the class the validator is in?


I have come across this issues a few times now and I'd like to know if there is something I can do to mitigate the issue.

When using a waterfall dialog or dialog for that matter there are validators you can add to the dialog. These are associated in the class you are running the dialog against. Seemingly. But upon runtime the validator seems to be separate from class in which it is in.

Here is an example.

 this.addDialog(new TextPrompt(SOME_PROMPT, this.validateSomething))
     .addDialog(new TextPrompt(SOME_PROMPT2, this.validateOtherthing))

And say your class has a property

public mutableProperty1 = true;

and in the validator

private async validateSomething(context) Promise<any> {
    if (something happens here) {
       this.mutableProperty1 = false
       return true
    }
    return false
}

But that doesn't happen. When the retry prompt occurs the property is never mutated to the desired results. Why is this and is there anything I can do to get it mutated as intended?


Solution

  • I believe this is more of a TypeScript/JavaScript question than a bot question. I suspect the problem is that the this keyword in the function does not refer to the object you think it does. Whenever you pass a function as a value without calling it, it's usually a good idea to bind the function to make sure this refers to the enclosing class instance.

    this.addDialog(new TextPrompt(SOME_PROMPT, this.validateSomething.bind(this)))
        .addDialog(new TextPrompt(SOME_PROMPT2, this.validateOtherthing.bind(this)))