Skip to content

Instantly share code, notes, and snippets.

@cramforce
Created July 20, 2020 18:34
Show Gist options
  • Save cramforce/755179c9a4903b58e0fc953a0c51b911 to your computer and use it in GitHub Desktop.
Save cramforce/755179c9a4903b58e0fc953a0c51b911 to your computer and use it in GitHub Desktop.
/**
* A `WeakRef` polyfill that works for DOM Elements only.
*
* NOTE, and this is a big NOTE, that the fallback implementation fails to
* `deref` an element if it is no longer in the respective document.
* Technically it could still be around, but for the purpose of this class
* we assume that the element is not longer reachable.
*/
export class DomBasedWeakRef {
/**
* @param {!Window} win
* @param {string} id
* @private
*/
constructor(win, id) {
this.win = win;
/** @private @const */
this.id_ = id;
}
/**
* Returns a WeakRef. Uses this implementation if the real WeakRef class
* is not available.
* @param {!Window} win
* @param {!Element} element
* @return {!WeakRef<!Element>|!DomBasedWeakRef<!Element>}
*/
static make(win, element) {
if (win.WeakRef) {
return new win.WeakRef(element);
}
if (!element.id) {
const index = (win.__weakrefId = (win.__weakrefId || 0) + 1);
element.id = 'weakref-id-' + index;
}
return new DomBasedWeakRef(win, element.id);
}
/** @return {!Element|undefined} */
deref() {
return this.win.document.getElementById(this.id_) || undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment