如何在自定义js对象上设置自己的处理程序事件?

问题描述

一个Interval,有以下用途:

let interval = new Interval(1000);
interval.ontick = function(progress){
    console.log('Progress:',progress);
};
interval.start(10);

在超时后一秒钟内start()内呼叫onTickEventHandler(),但是ontickundefined

function start(count) {
    _count = count;
    _intervalId = setInterval(onTickEventHandler,_timeout);
}

function onTickEventHandler() {
    if (_progress == _count) {
        reset();
        callEventHandler(onfinish);
        return;
    }

    callEventHandler(ontick,_progress++); // ontick is undefined
}

我这样尝试过

_intervalId = setInterval(onTickEventHandler.bind(this),_timeout);

this有我的interval.ontick,但在onTickEventHandler-ontick内是undefined

更新

我将let ontick更改为function ontick,并在各处使用this

可以简化吗?目标是对DOM元素做类似的事情:

button.onclick = function(){}
interval.ontick = function(){}

完整代码

const Interval = function (timeout) {
    const _timeout = timeout;

    let _intervalId;
    let _count;
    let _progress = 0;

    function ontick(){}
    function onpause(){}
    function onresume(){}
    function onfinish(){}

    function onTickEventHandler() {
        if (_progress == _count) {
            reset();
            callEventHandler(this.onfinish);
            return;
        }

        callEventHandler(this.ontick,_progress++);
    }

    function start(count) {
        _count = count;
        _intervalId = setInterval(onTickEventHandler.bind(this),_timeout);
    }

    function pause() {
        clearInterval(_intervalId);
        callEventHandler(this.onpause);
    }

    function resume() {
        this.start(_count);
        callEventHandler(this.onresume);
    }

    function reset() {
        clearInterval(_intervalId);
        _progress = 0;
    }

    function callEventHandler(handler,arg1){
        if (handler){
            handler(arg1);
        }
    }


    return {
        start: start,pause: pause,resume: resume,ontick: ontick,onpause: onpause,onresume: onresume,onfinish: onfinish,};
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)