@@ -6,6 +6,7 @@ import reactive from './core/reactive';
6
6
import render from './core/render' ;
7
7
8
8
import { setElementCustomProp } from './core/utils/elementCustomProp' ;
9
+ import { DIRECTIVE_PREFIX } from './models/generics' ;
9
10
10
11
export class Component {
11
12
public state : State ;
@@ -21,17 +22,18 @@ export class Component {
21
22
22
23
public mount ( el : HTMLElement | string ) : State {
23
24
// Accepts both selector and element reference
24
- const rootEl = typeof el === 'string' ? document . querySelector ( el ) : el ;
25
+ const rootEl =
26
+ typeof el === 'string' ? document . querySelector < HTMLElement > ( el ) ! : ( el as HTMLElement ) ;
25
27
const $render = ( deps : string [ ] = Object . keys ( this . state ) ) => this . render ( deps ) ;
26
28
27
- // AST generation
28
- this . ast = compile ( rootEl as HTMLElement , this . state ) ;
29
+ this . ast = compile ( rootEl , this . state ) ;
29
30
this . directives = { ...this . directives , ...directives } ;
30
31
this . state = reactive ( { ...this . state , $render } , this . render . bind ( this ) , this . watchers ) ;
31
32
32
33
this . render ( ) ;
33
34
34
- setElementCustomProp ( rootEl as HTMLElement , 'component' , this ) ;
35
+ setElementCustomProp ( rootEl , 'component' , this ) ;
36
+ this . handleMutations ( rootEl ) ;
35
37
36
38
return this . state ;
37
39
}
@@ -47,6 +49,25 @@ export class Component {
47
49
public render ( props : string [ ] = Object . keys ( this . state ) ) {
48
50
render ( this . ast ! , directives , this . state , props ) ;
49
51
}
52
+
53
+ public handleMutations ( el : HTMLElement ) {
54
+ const mutationObserver = new MutationObserver ( ( mutationsList ) => {
55
+ for ( const mutation of mutationsList ) {
56
+ const attrName = String ( mutation . attributeName ) ;
57
+ if (
58
+ mutation . type === 'attributes' &&
59
+ attrName . startsWith ( DIRECTIVE_PREFIX ) &&
60
+ attrName !== `${ DIRECTIVE_PREFIX } for`
61
+ ) {
62
+ this . ast = compile ( el , this . state ) ;
63
+ this . render ( ) ;
64
+ console . log ( 'render' ) ;
65
+ }
66
+ }
67
+ } ) ;
68
+
69
+ mutationObserver . observe ( el , { attributes : true , subtree : true } ) ;
70
+ }
50
71
}
51
72
52
73
export const component = ( state ?: State ) => new Component ( state ) ;
0 commit comments