如何解决如何在自定义js对象上设置自己的处理程序事件?
有一个Interval
,有以下用途:
let interval = new Interval(1000);
interval.ontick = function(progress){
console.log('Progress:',progress);
};
interval.start(10);
在超时后一秒钟内start()
内呼叫onTickEventHandler()
,但是ontick
是undefined
。
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 举报,一经查实,本站将立刻删除。