Skip to content

Commit e214e62

Browse files
committed
feat(datatable): enhance lifecycle management with reinitialization and disposal improvements
- Introduced `_disposed` flag to manage component state and prevent re-initialization of active instances. - Added `reinit()` static method for explicit re-initialization, cleaning up disposed instances as needed. - Improved disposal logic to ensure safe cleanup of event listeners and async operations.
1 parent bdceb26 commit e214e62

3 files changed

Lines changed: 519 additions & 8 deletions

File tree

src/components/component.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export default class KTComponent {
2626
protected _events: Map<string, Map<string, CallableFunction>>;
2727
protected _uid: string | null = null;
2828
protected _element: HTMLElement | null = null;
29+
protected _disposed: boolean = false;
2930

3031
protected _init(element: HTMLElement | null) {
3132
element = KTDom.getElement(element);
@@ -34,9 +35,25 @@ export default class KTComponent {
3435
return;
3536
}
3637

38+
// Check for existing instance
39+
const existingInstance = KTData.get(element, this._name) as
40+
| KTComponent
41+
| undefined;
42+
if (existingInstance) {
43+
// If instance exists and is not disposed, return early (idempotent initialization)
44+
if (!existingInstance._disposed) {
45+
return;
46+
}
47+
// If instance exists but is disposed, clean it up before re-initializing
48+
if (existingInstance._disposed && typeof existingInstance.dispose === 'function') {
49+
existingInstance.dispose();
50+
}
51+
}
52+
3753
this._element = element;
3854
this._events = new Map();
3955
this._uid = KTUtils.geUID(this._name);
56+
this._disposed = false;
4057

4158
this._element.setAttribute(`data-kt-${this._name}-initialized`, 'true');
4259

@@ -114,10 +131,26 @@ export default class KTComponent {
114131
}
115132

116133
public dispose(): void {
117-
if (!this._element) return;
134+
// Idempotent: can be called multiple times safely
135+
if (this._disposed || !this._element) return;
136+
137+
// Mark as disposed first to prevent re-entry
138+
this._disposed = true;
118139

140+
// Clean up event listeners
141+
if (this._events) {
142+
this._events.clear();
143+
}
144+
145+
// Remove data attribute
119146
this._element.removeAttribute(`data-kt-${this._name}-initialized`);
147+
148+
// Remove from data store
120149
KTData.remove(this._element, this._name);
150+
151+
// Clear references
152+
this._element = null;
153+
this._uid = null;
121154
}
122155

123156
public on(eventType: string, callback: CallableFunction): string {

0 commit comments

Comments
 (0)