Skip to content

Commit dff602d

Browse files
authored
Merge pull request #16 from github/private-state
Hide private instance state
2 parents 9bf99a4 + 83a1eab commit dff602d

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/index.ts

+23-16
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
class RemoteInputElement extends HTMLElement {
2-
currentQuery: string | null
3-
debounceInputChange: (event: Event) => void
4-
boundFetchResults: (event: Event) => void
1+
const states = new WeakMap()
52

3+
class RemoteInputElement extends HTMLElement {
64
constructor() {
75
super()
8-
this.currentQuery = null
9-
this.debounceInputChange = debounce(() => fetchResults(this))
10-
this.boundFetchResults = () => fetchResults(this)
6+
const fetch = fetchResults.bind(null, this, true)
7+
const state = {currentQuery: null, oninput: debounce(fetch), fetch}
8+
states.set(this, state)
119
}
1210

1311
static get observedAttributes() {
@@ -27,18 +25,24 @@ class RemoteInputElement extends HTMLElement {
2725
input.setAttribute('autocomplete', 'off')
2826
input.setAttribute('spellcheck', 'false')
2927

30-
input.addEventListener('focus', this.boundFetchResults)
31-
input.addEventListener('change', this.boundFetchResults)
32-
input.addEventListener('input', this.debounceInputChange)
28+
const state = states.get(this)
29+
if (!state) return
30+
31+
input.addEventListener('focus', state.fetch)
32+
input.addEventListener('change', state.fetch)
33+
input.addEventListener('input', state.oninput)
3334
}
3435

3536
disconnectedCallback() {
3637
const input = this.input
3738
if (!input) return
3839

39-
input.removeEventListener('focus', this.boundFetchResults)
40-
input.removeEventListener('change', this.boundFetchResults)
41-
input.removeEventListener('input', this.debounceInputChange)
40+
const state = states.get(this)
41+
if (!state) return
42+
43+
input.removeEventListener('focus', state.fetch)
44+
input.removeEventListener('change', state.fetch)
45+
input.removeEventListener('input', state.oninput)
4246
}
4347

4448
get input(): HTMLInputElement | HTMLTextAreaElement | null {
@@ -55,14 +59,17 @@ class RemoteInputElement extends HTMLElement {
5559
}
5660
}
5761

58-
async function fetchResults(remoteInput: RemoteInputElement, checkCurrentQuery: boolean = true) {
62+
async function fetchResults(remoteInput: RemoteInputElement, checkCurrentQuery: boolean) {
5963
const input = remoteInput.input
6064
if (!input) return
6165

66+
const state = states.get(remoteInput)
67+
if (!state) return
68+
6269
const query = input.value
63-
if (checkCurrentQuery && remoteInput.currentQuery === query) return
70+
if (checkCurrentQuery && state.currentQuery === query) return
6471

65-
remoteInput.currentQuery = query
72+
state.currentQuery = query
6673

6774
const src = remoteInput.src
6875
if (!src) return

0 commit comments

Comments
 (0)