最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - attributeChangedCallback not firing - Stack Overflow

programmeradmin1浏览0评论

problem is as follows, when I update the attr sticky either in the devtool or with js code I can't get the attributeChangedCallback to fire. The _updateSticky() method runs just fine when scrolling around, with adding and removing the sticky attr.

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);

problem is as follows, when I update the attr sticky either in the devtool or with js code I can't get the attributeChangedCallback to fire. The _updateSticky() method runs just fine when scrolling around, with adding and removing the sticky attr.

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);
Share Improve this question edited Feb 11, 2017 at 2:40 Xi Sigma 2,3722 gold badges14 silver badges18 bronze badges asked Feb 10, 2017 at 22:57 Björn HjorthBjörn Hjorth 2,8885 gold badges26 silver badges32 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 21

It's just that you have a typo: observedAttribute should be observedAttributes.

发布评论

评论列表(0)

  1. 暂无评论