Skip to content

Instantly share code, notes, and snippets.

@zzzgit
Last active September 3, 2019 03:49
Show Gist options
  • Save zzzgit/25fdfc136ccc65fbb1cc56289d6c13f4 to your computer and use it in GitHub Desktop.
Save zzzgit/25fdfc136ccc65fbb1cc56289d6c13f4 to your computer and use it in GitHub Desktop.
watcher implements in lit-element
attributeChangedCallback(attr, oldValue, newValue) {
super.attributeChangedCallback(attr, oldValue, newValue)
if (!this.watch || !this.watch.apply) {
return null
}
if (!this._watch) {
this._watch = this.watch()
}
if (this._watch.hasOwnProperty(attr)) {
const watcher = this._watch[attr]
watcher.bind(this, newValue, oldValue)()
}
}
watch(targetNode, prop, cback) {
const callback = function (mutationsList, observer) {
const mutation = mutationsList.find(item => item.attributeName === prop)
if (mutation) {
cback(mutation)
}
}
// observer.disconnect()
const observer = new MutationObserver(callback)
observer.observe(targetNode, { attributes: true, childList: false, subtree: false })
}
updated(changedProperties) {
if (!this.watch || !this.watch.apply) {
return null
}
if (!this._watch) {
this._watch = this.watch()
}
changedProperties.forEach((oldValue, attr) => {
if (this._watch.hasOwnProperty(attr)) {
const watcher = this._watch[attr]
watcher.bind(this, this[attr], oldValue)()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment