Skip to content

Commit 9807527

Browse files
authored
Merge pull request #165 from github/controller-manages-instance-tracking
Refactor controller contents into `src/core`
2 parents df3b6a4 + 23b2b41 commit 9807527

2 files changed

Lines changed: 29 additions & 13 deletions

File tree

src/controller.ts

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
import {register} from './register.js'
2-
import {bind, bindShadow} from './bind.js'
3-
import {autoShadowRoot} from './auto-shadow-root.js'
4-
import {defineObservedAttributes, initializeAttrs} from './attr.js'
1+
import {initializeInstance, initializeClass} from './core.js'
52
import type {CustomElement} from './custom-element.js'
6-
73
/**
84
* Controller is a decorator to be used over a class that extends HTMLElement.
95
* It will automatically `register()` the component in the customElement
@@ -13,13 +9,7 @@ import type {CustomElement} from './custom-element.js'
139
export function controller(classObject: CustomElement): void {
1410
const connect = classObject.prototype.connectedCallback
1511
classObject.prototype.connectedCallback = function (this: HTMLElement) {
16-
this.toggleAttribute('data-catalyst', true)
17-
autoShadowRoot(this)
18-
initializeAttrs(this)
19-
bind(this)
20-
if (connect) connect.call(this)
21-
if (this.shadowRoot) bindShadow(this.shadowRoot)
12+
initializeInstance(this, connect)
2213
}
23-
defineObservedAttributes(classObject)
24-
register(classObject)
14+
initializeClass(classObject)
2515
}

src/core.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import {register} from './register.js'
2+
import {bind, bindShadow} from './bind.js'
3+
import {autoShadowRoot} from './auto-shadow-root.js'
4+
import {defineObservedAttributes, initializeAttrs} from './attr.js'
5+
import type {CustomElement} from './custom-element.js'
6+
7+
const instances = new WeakSet<Element>()
8+
9+
export function initializeInstance(instance: HTMLElement, connect?: (this: HTMLElement) => void): void {
10+
instance.toggleAttribute('data-catalyst', true)
11+
instances.add(instance)
12+
autoShadowRoot(instance)
13+
initializeAttrs(instance)
14+
bind(instance)
15+
if (connect) connect.call(instance)
16+
if (instance.shadowRoot) bindShadow(instance.shadowRoot)
17+
}
18+
19+
export function initializeClass(classObject: CustomElement): void {
20+
defineObservedAttributes(classObject)
21+
register(classObject)
22+
}
23+
24+
export function initialized(el: Element): boolean {
25+
return instances.has(el)
26+
}

0 commit comments

Comments
 (0)