attributeChangedCallback 未触发
attributeChangedCallback not firing
问题如下,当我在 devtool 中或使用 js 代码更新 attr sticky 时,我无法触发 attributeChangedCallback。
_updateSticky() 方法在滚动时运行良好,添加和删除粘性属性。
class HeaderLogo extends HTMLElement {
static get observedAttribute() {
return ['alt-logo', 'sticky'];
}
constructor() {
super();
}
connectedCallback() {
this._updateSticky();
window.addEventListener('scroll', () => {
this._updateSticky();
}, false);
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log("attr changed");
}
/* evaluates if the logo should be in sticky state or not */
_updateSticky() {
let scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
let breakpoint = 50;
if (scrollTop > breakpoint) {
this.setAttribute('sticky', '');
} else {
this.removeAttribute('sticky');
}
}
}
window.customElements.define('header-logo', HeaderLogo);
只是你打错了:observedAttribute
应该是observedAttributes
。
问题如下,当我在 devtool 中或使用 js 代码更新 attr sticky 时,我无法触发 attributeChangedCallback。 _updateSticky() 方法在滚动时运行良好,添加和删除粘性属性。
class HeaderLogo extends HTMLElement {
static get observedAttribute() {
return ['alt-logo', 'sticky'];
}
constructor() {
super();
}
connectedCallback() {
this._updateSticky();
window.addEventListener('scroll', () => {
this._updateSticky();
}, false);
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log("attr changed");
}
/* evaluates if the logo should be in sticky state or not */
_updateSticky() {
let scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
let breakpoint = 50;
if (scrollTop > breakpoint) {
this.setAttribute('sticky', '');
} else {
this.removeAttribute('sticky');
}
}
}
window.customElements.define('header-logo', HeaderLogo);
只是你打错了:observedAttribute
应该是observedAttributes
。