Add replace and replaced events to reactive elements

This commit is contained in:
Talia 2024-02-29 15:29:20 +01:00
parent 3ff99bee9b
commit d53e6c7fd5

View file

@ -118,6 +118,22 @@ const toElement = value => {
return reactiveElement(value) return reactiveElement(value)
} }
class ReplaceEvent extends Event {
/** @param {Element|Text} next */
constructor(next) {
super("replace", {bubbles: true, cancelable: true})
this.next = next
}
}
class ReplacedEvent extends Event {
/** @param {Element|Text} next */
constructor(next) {
super("replaced")
this.next = next
}
}
/** /**
* @param {Observable} observable * @param {Observable} observable
* @return {Element|Text} * @return {Element|Text}
@ -128,7 +144,10 @@ export const reactiveElement = observable => {
const ref = new WeakRef(element) const ref = new WeakRef(element)
observable.addEventListener("change", () => { observable.addEventListener("change", () => {
const next = reactiveElement(observable) const next = reactiveElement(observable)
ref.deref()?.replaceWith(next) const element = ref.deref()
if (element.dispatchEvent(new ReplaceEvent(next)))
element.replaceWith(next)
element.dispatchEvent(new ReplacedEvent(next))
}, {once: true}) }, {once: true})
return element return element
} }