javascript - 将类绑定到另一个类的实例
问题描述
我正在构建一个使用多个计时器(数字、模拟)的 JS 应用程序。我想使用Timer
具有以下功能的基类:启动、停止、更新等。
每次创建计时器时,也会onChange
创建新事件。因此,当计时器滴答时,多个实例会获得更新,而不仅仅是创建计时器的那个。
我的问题是:如何绑定和Timer
实例化另一个类?
定时器类:
class Timer = {
constructor() {
this.seconds = 0;
}
start() {
this.timer = setInterval(update, 25);
}
stop() {
clearInterval(this.timer);
}
update() {
this.seconds += 1;
//emit data
let event = new Event("timer-tick");
event.detail = {
seconds: seconds,
}
document.body.dispatchEvent(event);
}
}
数字定时器类:
class DigitalTimer = {
constructor() {
this.timer = new Timer();
this.handleEvent();
}
handleEvent() {
$('body').on('timer-tick', function(e) {
//tick, do somehting with it.
});
}
start() {
this.timer.start();
}
stop() {
this.timer.stop()
}
}
解决方案
on
我确实通过在一个普通对象上绑定一个andtrigger
事件
来让它工作。http://api.jquery.com/jQuery/#working-with-plain-objects
工作样本: https ://jsfiddle.net/q5s6cud3/
class Timer {
constructor() {
let self = this;
this.timer = setInterval(function() {
self.update();
}, 1000);
}
update() {
$(this).trigger('timer-tick');
}
}
class DigitalTimer {
constructor() {
this.timer = new Timer();
$(this.timer).on('timer-tick', function() {
console.log('yes');
});
}
}
const digitalTImer = new DigitalTimer();
推荐阅读
- php - Google Pay API for Pass
- android - ViewModel 启动和 withContext 未解析的引用
- php - ContextErrorException 注意:未定义索引:ps_sharebuttons.php 第 138 行中的产品
- button - 如果按钮被禁用,那么我想跳过单击它,如果它启用,我想使用 cypress 点击
- python - 在条件之后迭代地为 df.column 赋值
- linux - 基本 if 语句将无法正确执行
- python - 在谷歌协作脚本的断开连接事件上执行命令
- php - 单击搜索按钮时,所选选项未插入到我的 PHP 文件中,因此查询未执行
- php - PHP将两个数组的大小调整为相同的大小
- heroku - 将带有socketIO的python烧瓶聊天应用程序部署到heroku时出现代码= H12状态= 503错误