首页 > 解决方案 > 将类绑定到另一个类的实例

问题描述

我正在构建一个使用多个计时器(数字、模拟)的 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()
    }
}

标签: javascriptjquery

解决方案


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();

推荐阅读