Add replace and replaced events to reactive elements
This commit is contained in:
parent
3ff99bee9b
commit
d53e6c7fd5
1 changed files with 20 additions and 1 deletions
21
skooma.js
21
skooma.js
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue