#Calling an instance of a class within a function passed into process.stdin.on

7 messages · Page 1 of 1 (latest)

paper rivet
#

I have an abstract parent class Menu which passes a method (input) through process.stdin.on.

abstract class Menu extends RenderObject {
    label: string;

     constructor(label, priority, name) {
            super(priority, name);
            this.label = label;
            stdin.setRawMode(true);
            stdin.setEncoding(‘utf-8’);
            stdin.on(‘data’, this.input);
    }

    abstract input(data: Buffer);
}

Within an implementation of that method, i am attempting to call this to reference an instance of the class.

input(data: any) {
    switch(data){
        case “<Arrow Up>”:
            this.idx—;
            break;
        case “<Arrow Down>:
            this.idx++;
            break;
        caseCtrl+C”:
            process.exit();
        default:
            return;
    }
    Renderer.render();
}

However this refers to stdin itself. (As I’ve verified by logging, won’t provide it here since it’s just process.stdin.

I’ve attempted passing the instance as a parameter in the function

input(data: any, host = this)

This pointed back to process.stdin.
And also attempted to set input via an arrow function

input = (data) => {/* code */}

This flagged typescripts checking regarding improper implementation and through “listener argument must be of type function” as an error.

How do i get around this?

All help is appreciated, thank you very much heart_hug_

abstract venture
#

This would work:

stdin.on(‘data’, (data) => this.input(data));
#

How this works in Javascript is that when you call a function like obj.func(), then func is called with obj as this.

paper rivet
#

Ill have a test of this, thanks :)

abstract venture
#

Often helpful to think of it as an implicit parameter, it's like obj.func(arg) is equivalent to func(obj, arg) where the first argument is the "this" argument.

paper rivet
#

Works, thank you

abstract venture
#

BTW, you may want to look at your TSConfig and check your strictness settings.