From 4f4e8970ca7d9a585c1ae3b36365813c02e2b4a3 Mon Sep 17 00:00:00 2001 From: yutent Date: Tue, 19 Sep 2023 18:35:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=BC=82=E5=B8=B8=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/index.js | 21 ++++++++++++++++----- src/utils.js | 10 +++++++--- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index b567183..fb52421 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wkit", - "version": "1.10.7", + "version": "1.10.8", "type": "module", "description": "A library for building fast, lightweight web components.", "main": "dist/index.js", diff --git a/src/index.js b/src/index.js index ae8c6f4..82fe54b 100644 --- a/src/index.js +++ b/src/index.js @@ -259,7 +259,7 @@ export class Component extends HTMLElement { disconnectedCallback() { if (this.keepAlive) { - this.deactivated() + this.#asyncCallSafety(this.deactivated) } else { this[__children__]?.setConnected(false) @@ -276,7 +276,7 @@ export class Component extends HTMLElement { window.wkitd.deassign(this) } } - this.unmounted() + this.#asyncCallSafety(this.unmounted) } } // 监听属性变化 @@ -386,11 +386,11 @@ export class Component extends HTMLElement { this.$animate() } if (this.keepAlive) { - nextTick(_ => this.activated()) + this.#asyncCallSafety(this.activated) } - nextTick(_ => this.mounted()) + this.#asyncCallSafety(this.mounted) } else { - nextTick(_ => this.updated(props)) + this.#asyncCallSafety(this.updated, props) } } @@ -411,6 +411,17 @@ export class Component extends HTMLElement { console.error(err) } } + + #asyncCallSafety(callback, arg) { + nextTick(_ => { + try { + callback.call(this, arg) + } catch (err) { + console.error(err) + } + }) + } + // 几个生命周期回调 created() {} mounted() {} diff --git a/src/utils.js b/src/utils.js index ff444d6..f21c291 100644 --- a/src/utils.js +++ b/src/utils.js @@ -79,12 +79,16 @@ export function offset(node) { /** * 事件绑定 */ -export function bind(dom, type, selector, fn, phase = true) { +export function bind(dom, type = '', selector, fn, phase = true) { let events = type.split(',') let callback - let isWc = dom.host === dom + let isWc = dom && dom.host === dom let host = isWc ? dom : null + if (!dom || !type) { + return console.error('call bind: argument error') + } + if (typeof selector === 'function') { phase = fn fn = selector @@ -147,7 +151,7 @@ export function bind(dom, type, selector, fn, phase = true) { /** * 解除事件绑定 */ -export function unbind(dom, type, fn = noop, phase = false) { +export function unbind(dom, type = '', fn = noop, phase = false) { let events = type.split(',') events.forEach(function (t) { dom.removeEventListener(t.trim(), fn, phase)