首页 > 解决方案 > 将可选函数分配给 Javascript 类

问题描述

我正在创建一个简单的 Javascript 类,我基本上希望在start()进程的某些区域拥有“事件侦听器”。我在一个文件中有一个类,并在另一个文件中创建该类的一个实例。然后我想在类的一部分上附加一个监听器,如果用户向类监听器提供一个函数,然后执行它。

myClass.js

export class MyClass {
  constructor() {
    this.beforeStart = null;
    this.started = null;
    this.beforeEnd = null;
    this.ended = null;
  }

  async start() {
    if (typeof this.beforeStart == 'function') await this.beforeStart();

    // .....start logic here..
    console.log('start logic here..');

    if (typeof this.started == 'function') await this.started();
  }

  async end() {
    if (typeof this.beforeEnd == 'function') await this.beforeEnd();

    // .....end logic here..
    console.log('end logic here..');

    if (typeof this.ended == 'function') await this.ended();
  }
  
}

main.js

const nClass = new MyClass();
nClass.beforeStart = () => {
  console.log('await beforeStart work here');
};
nClass.started = () => {
  console.log('await started work here');
};
nClass.beforeEnded = () => {
  console.log('await beforeEnded work here');
};
nClass.ended = () => {
  console.log('await ended work here');
};
nClass.start();
nClass.end();

我希望能够等待侦听器,以便用户可以在“侦听器”挂钩中执行各种任务。

标签: javascript

解决方案


@lawrence-witt 提交的答案

这个解决方案非常适合我。

 const halt = msg => {
    return new Promise(res => {
    setTimeout(() => {
        console.log(msg);
      res();
    }, 1000)
  });
};

class MyClass {
  constructor() {
    this.beforeStart = null;
    this.started = null;
    this.beforeEnd = null;
    this.ended = null;
  }

  async start() {
    if (typeof this.beforeStart == 'function') await this.beforeStart();

    // .....start logic here..
    console.log('executing start logic');

    if (typeof this.started == 'function') await this.started();
  }

  async end() {
    if (typeof this.beforeEnd == 'function') await this.beforeEnd();

    // .....end logic here..
    console.log('executing end logic');

    if (typeof this.ended == 'function') await this.ended();
  }
};

const nClass = new MyClass();
nClass.beforeStart = async () => {
    await halt('beforeStart complete');
};
nClass.started = async () => {
    await halt('started complete');
};
nClass.beforeEnd = async () => {
    await halt('beforeEnd complete');
};
nClass.ended = async () => {
    await halt('ended complete');
};

const run = async () => {
    await nClass.start();
  await nClass.end();
};

run();

推荐阅读