Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - 将类绑定到另一个类的实例(Bind class to an instance of another class)

I'm building an JS application where I'm using multiple timers (digital, analog).

(我正在构建一个使用多个计时器(数字,模拟)的JS应用程序。)

I would like to use a base class for the Timer with the functions: start, stop, update, etc.

(我想使用具有以下功能的Timer基类:启动,停止,更新等。)

Every time there is a timer created there are also new onChange event created.

(每次创建一个计时器时,都会创建一个新的onChange事件。)

So when the timer ticks multiple instances get an update, not only the one where the timer is created in.

(因此,当计时器计时时,多个实例将获得更新,而不仅仅是其中创建计时器的实例。)

My question is: how can I bind and Timer instance the another class?

(我的问题是:如何绑定另一个实例的Timer实例?)

Timer class:

(计时器类:)

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

DigitalTimer class:

(DigitalTimer类:)

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()
    }
}
  ask by JeroenR translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did get it working by binding an on and trigger event on a plain object.

(我确实通过在普通对象上绑定ontrigger事件来使其工作。)

http://api.jquery.com/jQuery/#working-with-plain-objects

(http://api.jquery.com/jQuery/#working-with-plain-objects)

Working sample: https://jsfiddle.net/q5s6cud3/

(工作示例: 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...