From 887301d3a71be3792e2d94cdc384f909b91fd4dc Mon Sep 17 00:00:00 2001 From: lijiacheng Date: Thu, 6 Feb 2025 11:57:36 +0800 Subject: [PATCH] =?UTF-8?q?feature:=E6=94=AF=E6=8C=81destroy=E6=96=B9?= =?UTF-8?q?=E6=B3=95,=E9=94=80=E6=AF=81dom=E7=9A=84contextmenu=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E7=9B=91=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/index.ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 568fcf9..7da0691 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,12 +16,15 @@ export default class RightMenu { private version: string = version private menu: HTMLElement | null = null private config: ConfigType + private options: OptionsType private eventList: Array<[Window | Document, string, LiType['callback']]> = [] private menuStyle = { 'min-width': '', 'max-width': '', } + private bindEl: Element | null = null + constructor( el: ConfigType, options: OptionsType, @@ -40,12 +43,25 @@ export default class RightMenu { if (config.maxWidth) { this.menuStyle['max-width'] = getValue(config.maxWidth) } + this.options = options + // 获取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) - }) + this.bindEl = dom + + this.contextMenuHandler = this.contextMenuHandler.bind(this) + + dom?.addEventListener('contextmenu', this.contextMenuHandler) + } + + contextMenuHandler(e: Event) { + const { options, config } = this + const res = typeof options === 'function' ? options(e, config) : options + this.init(e as MouseEvent, res) + } + + destroy() { + this.bindEl?.removeEventListener('contextmenu', this.contextMenuHandler) } /**