0

I have a list of tokens storing the contents of an editor. Each node in the list has a map of dom nodes. Why a map? Because the same block of text could appear in multiple places in the page and I want all instances kept in sync by the same data structure.

In those maps of dom nodes, I would like to use the container dom node as a key in a WeakMap on each node of the doubly linked list, where the value is the dom node for that list node's token. This way, if an instance of the editor is cleared from the dom (and the container registry), the list will lose all references to the individual token nodes without the need of iterating over the list to manually remove the reference in the map.

Here is a toy example of what I'm talking about:

let containers = new Set([])

let container1 = document.createElement('div')
let container2 = document.createElement('div')
containers.add(container1)
containers.add(container2)

let root = document.getElementById('root')
root.append(container1)
root.append(document.createElement('hr'))
root.append(container2)

let tokens = ['foo', 'bar', 'baz']
let head = {};
let list_node = head;
for (let token of tokens) {
  list_node.token = token;
  list_node.dom = new WeakMap()

  containers.forEach(container_node => {
    let token_node = document.createElement('span')
    token_node.textContent = list_node.token
    list_node.dom.set(container_node, token_node)
    container_node.append(token_node)
  })

  list_node.next = {}
  list_node = list_node.next
}

https://jsfiddle.net/ujs6vpfq/3/

The question I have is, if I am using the same dom container node as a key in multiple WeakMaps, will that constitute multiple references and prevent garbage collection? I know of no way to test this because WeakMaps can't be interrogated to find what values they hold.

theSherwood
  • 1
  • 1
  • 2

0 Answers0