javascript / expert
Snippet
Polymorphic State Evaluation via Abstract Handler Inheritance in Svelte Action Directives
By pairing Object-Oriented polymorphism and ES6 class inheritance with Svelte node actions, dynamic behaviors can be injected into DOM elements while ensuring clean teardown lifecycles through polymorphism.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class BaseInteractionHandler {constructor(node) {this.node = node;}handleEvent(event) {throw new Error('Abstract method handleEvent must be overridden');}destroy() {}}class HoverInteractionHandler extends BaseInteractionHandler {constructor(node) {super(node);this.onPointerEnter = (e) => this.handleEvent(e);this.node.addEventListener('pointerenter', this.onPointerEnter);}handleEvent(event) {this.node.dataset.hovered = 'true';}destroy() {this.node.removeEventListener('pointerenter', this.onPointerEnter);}}export function polymorphicAction(node, HandlerClass = HoverInteractionHandler) {const instance = new HandlerClass(node);return {destroy() {instance.destroy();}};}
svelte
Breakdown
1
class BaseInteractionHandler
Defines an abstract OOP interface contract for DOM node lifecycle and event handling.
2
class HoverInteractionHandler extends BaseInteractionHandler
Concrete subclass extending base behavior to encapsulate hover state logic.
3
export function polymorphicAction(node, HandlerClass = HoverInteractionHandler)
Svelte action directive instantiation factory receiving polymorphic class constructors.
4
instance.destroy();
Delegates node cleanup responsibility directly to the instantiated class strategy.