Created
July 20, 2020 18:34
-
-
Save cramforce/755179c9a4903b58e0fc953a0c51b911 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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