canvas-nest.js
canvas-nest.js copied to clipboard
bindEvent里为什么要写 this.onmousemove && this.onmousemove(e); 这一句呢?
您好,看了代码以后这一处地方不是很理解:
//绑定事件 bindEvent(){ ... this.onmousemove = window.onmousemove; window.onmousemove = e => { this.current.x = e.clientX - this.el.offsetLeft + document.scrollingElement.scrollLeft; this.current.y = e.clientY - this.el.offsetTop + document.scrollingElement.scrollTop; this.onmousemove && this.onmousemove(e); }; ... }
为什么要在这里调用一下 this.onmousemove 方法? 我的疑惑是: 第一次调用bindEvent,这里的 window.onmousemove是 null,那么这一句不会执行;而如果第二次执行(不先destroy的情况下),会造成死循环。望指教 ^_^
就我个人对代码的理解,this.on... = window.on... 是在把原本 window 对滑鼠移动的监听函数暂存起来,下面对window.on... 是先用自订的函数覆盖过去。
而之所以要呼叫 this.on... && this.on...(e) 是类似 class 中呼叫 super() 的概念,也就是呼叫原本 window 对滑鼠的监听函数。
整句的意思是:如果原本有 window 对滑鼠的监听函数,则在执行自定义动作后呼叫原函数。
最后在下方的 destroy() 函数中才再利用赋值将 window 原有的监听函数还回去。
希望有帮上忙。