javascript - 将可选函数分配给 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();
我希望能够等待侦听器,以便用户可以在“侦听器”挂钩中执行各种任务。
解决方案
@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();
推荐阅读
- c++ - 在自定义容器中实现迭代器和反向迭代器以支持 STL 的 API 是什么?
- python - 在网页 HTML 中加入日期时间 - Python、Jinja
- mysql - WordPress 查询,meta_query,比较 BETWEEN,没有结果
- laravel - Laravel Livewire 2.6:间接修改 Illuminate\Database\Eloquent\Collection 的重载元素无效
- sql - Oracle SQL - 小时数
- angular - eslint angular - 找不到 .eslintrc
- javascript - 在反应原生 Hermes 引擎中增加了应用程序的大小
- reactjs - 使用 API 响应触发模式
- jwt - 如何使用 JWS Detached 验证 HTTP 消息
- javascript - 对这个 php 代码从 zepto 到 jquery 的转换有一些帮助吗?