Skip to content

Commit 2547e7f

Browse files
authored
Merge pull request #106 from github/optimize-memory-for-bind
refactor(bind): optimize memory by using WeakSet over Set
2 parents 7f546f0 + 195b8c2 commit 2547e7f

2 files changed

Lines changed: 9 additions & 7 deletions

File tree

src/bind.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
const controllers = new Set<string>()
1+
const controllers = new WeakSet<Element>()
22

33
/*
44
* Bind `[data-action]` elements from the DOM to their actions.
55
*
66
*/
77
export function bind(controller: HTMLElement): void {
8-
controllers.add(controller.tagName.toLowerCase())
8+
controllers.add(controller)
99
if (controller.shadowRoot) {
1010
bindElements(controller.shadowRoot)
1111
listenForBind(controller.shadowRoot)
@@ -72,14 +72,14 @@ function bindElements(root: Element | ShadowRoot) {
7272
function handleEvent(event: Event) {
7373
const el = event.currentTarget as Element
7474
for (const binding of bindings(el)) {
75-
if (event.type === binding.type && controllers.has(binding.tag)) {
76-
type EventDispatcher = Element & Record<string, (ev: Event) => unknown>
77-
const controller = el.closest(binding.tag) as EventDispatcher
78-
if (controller && typeof controller[binding.method] === 'function') {
75+
if (event.type === binding.type) {
76+
type EventDispatcher = HTMLElement & Record<string, (ev: Event) => unknown>
77+
const controller = el.closest<EventDispatcher>(binding.tag)!
78+
if (controllers.has(controller) && typeof controller[binding.method] === 'function') {
7979
controller[binding.method](event)
8080
}
8181
const root = el.getRootNode()
82-
if (root instanceof ShadowRoot && root.host.matches(binding.tag)) {
82+
if (root instanceof ShadowRoot && controllers.has(root.host) && root.host.matches(binding.tag)) {
8383
const shadowController = root.host as EventDispatcher
8484
if (typeof shadowController[binding.method] === 'function') {
8585
shadowController[binding.method](event)

test/bind.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ describe('bind', () => {
204204
describe('listenForBind', () => {
205205
it('re-binds actions that are denoted by HTML that is dynamically injected into the controller', async function () {
206206
const instance = document.createElement('bind-test-element')
207+
bind(instance)
207208
chai.spy.on(instance, 'foo')
208209
root.appendChild(instance)
209210
listenForBind(root)
@@ -278,6 +279,7 @@ describe('bind', () => {
278279

279280
it('re-binds actions deeply in the HTML', async function () {
280281
const instance = document.createElement('bind-test-element')
282+
bind(instance)
281283
chai.spy.on(instance, 'foo')
282284
root.appendChild(instance)
283285
listenForBind(root)

0 commit comments

Comments
 (0)