diff --git a/packages/svelte-imask/src/action.ts b/packages/svelte-imask/src/action.ts index 13441260..cca46afa 100644 --- a/packages/svelte-imask/src/action.ts +++ b/packages/svelte-imask/src/action.ts @@ -7,7 +7,7 @@ function fireEvent (el: HTMLElement, eventName: string, el.dispatchEvent(e); } -function initMask (el: HTMLElement, opts: InputMask | Opts) { +function initMask (el: HTMLElement, opts: InputMask | Opts): InputMask { const maskRef = (opts instanceof IMask.InputMask ? opts : IMask(el, opts as Opts)); return maskRef .on('accept', () => fireEvent(el, 'accept', maskRef)) @@ -17,23 +17,26 @@ function initMask (el: HTMLElement, opts: InputMask (el: HTMLElement, opts: Opts) { - let maskRef: InputMask | undefined = opts && initMask(el, opts); + let maskRef: InputMask | undefined; + let created: boolean | undefined; function destroy (): void { - if (maskRef) { - maskRef.destroy(); - maskRef = undefined; - } + if (created) maskRef?.destroy(); + maskRef = undefined; + created = undefined; } function update (opts: InputMask | Opts | UpdateOpts): void { if (!opts) return destroy(); - if (opts instanceof IMask.InputMask) maskRef = opts; - else if (maskRef) maskRef.updateOptions(opts as UpdateOpts); - else maskRef = initMask(el, opts as Opts); + if (opts instanceof IMask.InputMask || !maskRef) maskRef = initMask(el, opts as Opts); + else maskRef.updateOptions(opts as UpdateOpts); + + created = (opts as InputMask) !== maskRef; } + update(opts); + return { update, destroy,