right-menu icon indicating copy to clipboard operation
right-menu copied to clipboard

如何在需要的特定场景下,销毁contextmenu事件监听

Open Simon7520 opened this issue 1 year ago • 0 comments

构造函数中:

// 获取dom并绑定事件
const dom = typeof config.el === 'string' ? document.querySelector(config.el) : config.el
dom?.addEventListener('contextmenu', (e) => {
  const res = typeof options === 'function' ? options(e, config) : options
  this.init(e as MouseEvent, res)
})

希望增加destroy方法,使开发者能够主动移除事件监听。改造示例如下:

// 获取dom并绑定事件
const dom = typeof config.el === 'string' ? document.querySelector(config.el) : config.el
this.dom = dom;
this.contentMenuHandler = (e) => {
  const res = typeof options === 'function' ? options(e, config) : options
  this.init(e as MouseEvent, res)
}
dom?.addEventListener('contextmenu', this.contentMenuHandler)

...

destroy(){
  this.dom.removeEventListener('contextmenu', this.contentMenuHandler)
}

具体场景: 在与vxe-table搭配使用时,监听器的init方法中调用的自定义的preventDefault函数源码中包含stopPropagation阻止冒泡,导致第二次之后的点击事件冒泡事件无法触发。而我希望触发事件来完成我的逻辑效果。

Simon7520 avatar Oct 18 '23 07:10 Simon7520