Получение / установка функции как свойства класса (TypeScript) - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь создать класс, который выглядит следующим образом:

class Foo {
  _bar?: () => void; // this is a property which will invoke a function, if it is defined

  set bar(barFunctionDef: () => void) { // this stores a reference to the function which we'll want to invoke
    this._bar = barFunctionDef;
  }

  get bar() { // this should either invoke the function, or return a reference to the function so that it can be invoked
    return this._bar;
  }

  doSomething() { // this is what will be called in an external class
    if(condition) {
      this.bar; // this is where I would like to invoke the function (bar)
    }
  }
}

По сути, я хочу иметь класс, который будет хранить ссылки на функции, которые будут установлены по желанию. Будет много свойств класса "bar", которые будут иметь тип () => void.

. Есть ли "правильный" способ вызова this.bar внутри doSomething, чтобы вызвать функцию, которая хранится на это имущество?

1 Ответ

0 голосов
/ 28 апреля 2020

Не знаю, достигаете ли вы этого, но я создал пример реализации c generi здесь

type MethodReturnsVoid = () => void;

class Foo {
  methods: Map<string, MethodReturnsVoid>;

  constructor() {
    this.methods = new Map();
  }

  public getMethod(methodName: string): MethodReturnsVoid {
    if (this.methods.has(methodName)) {
      return this.methods.get(methodName);
    }

    return null;
  }

  public setMethod(methodName: string, method: () => void): void {
    this.methods.set(methodName, method);
  }
}

const foo = new Foo();
const func: MethodReturnsVoid = () => console.log('func');
const anotherFunc: MethodReturnsVoid = () => console.log('anotherFunc');

foo.setMethod('func', func);
foo.setMethod('anotherFunc', anotherFunc);

const methodFunc = foo.getMethod('func');
if (methodFunc) methodFunc();

const methodAnotherFunc = foo.getMethod('anotherFunc');
if (methodAnotherFunc) methodAnotherFunc();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...