向JavaScript对象添加“自定义”功能

时间:2018-07-22 18:19:27

标签: javascript countdown

很抱歉这个模糊的问题,但不确定如何措辞。

我正在创建一个计时器(带有进度条,从100%变为0),我想添加类似“ onStop”的功能供用户使用。计时器达到0后将调用此函数。如何将其添加到类中?

当前代码:

"use strict";

const progressBar = { 

    // Default config, set to countdown starting at 3 minutes
    config: { 
        //  Define time in seconds 
        time: 180, // 3 minutes
        // Wrapper
        wrapper: '',
        // New element that will be the actual progress bar inside the wrapper
        bar: ''
    },

    //onStop: function() { console.log('triggered'); }, // custom function
    onStart: function() {}, // custom function

    bind: function(el) {
        this.createBar(el);
    },

    createBar: function(el) {
        const wrapper = document.getElementById(el);
        const bar = document.createElement("div");
        this.config.bar = bar;
        this.config.bar.id = "progressbar-inside";
        this.config.bar.style.width = '100%';
        this.config.bar.style.height = '100%';
        wrapper.appendChild(bar);
    },

    start: function() {
        //const percentage = 0.55
        const percentage = 100 / this.config.time;
        const time = this.config.time;
        progressBar.countDown(percentage, '100', time-1);
    },

    countDown: function(percentage, width, time) {
        const new_time = time-1;
        const new_width = width - percentage;
        this.config.bar.style.width = new_width + '%'

        console.log(time);  

        if (time === 0) {
            progressBar.onStop();
            return;
        }

        setTimeout(function() {
            progressBar.countDown(percentage, new_width, new_time)
        }, 1000);
    }

}

有人可以这样使用:

progressBar.bind('progressbar');
progressBar.config.time = 25;
progressBar.start();

如果要允许最终用户这样做,应该添加什么内容

progressBar.onStop(function() {
 // Timer finished! Do stuff here
});

1 个答案:

答案 0 :(得分:2)

在数组内部收集停止处理程序:

stopHandlers: [],

然后在调用onStop时,只需将函数推入该数组即可:

onStop(fn) { this.stopHandlers.push(fn); },

然后触发它们(在某些方法内部):

   this.stopHandlers.forEach(fn => fn());