将 'custom' 函数添加到 javascript 对象

Add 'custom' function to javascript object

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

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

当前代码:

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

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

stopHandlers: [],

然后当 onStop 被调用时,只需将函数推送到该数组:

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

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

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