2017-01-18 68 views
3

我正在構建一個簡單的自定義元素,使用custom elements polyfill。我已經註冊了一個屬性「被監視」(使用observedAttributes()),當我改變這個屬性的值時,函數attributeChangedCallback被調用兩次。爲什麼attributeChangedCallback調用兩次?

下面是HTML代碼:

<my-component id="compo" foo="bar"></my-component> 

<button id="myBtn">Change attribute value</button> 

這裏是我的組件定義:

class MyComponent extends HTMLElement { 
    constructor() { 
    super(); 
    } 

    static get observedAttributes() { 
    return ['foo']; 
    } 

    attributeChangedCallback(attrName, oldVal, newVal) { 
    console.log('[my component] attribute', attrName, 'changed from', oldVal, 'to', newVal); 
    } 
} 

window.customElements.define('my-component', MyComponent); 

// Change value of the component attribute 
$('#myBtn').click(() => $('#compo').attr('foo', 'baz')); 

在該頁面中,當我點擊按鈕,我在console.log以下日誌:

[my component]屬性foo從bar變成baz

[我的組件]屬性FOO從酒吧改爲巴茲

爲什麼attributeChangedCallback調用兩次?我怎樣才能避免它?

這個例子中的的jsfiddle是在這裏:https://jsfiddle.net/czo1355c/

感謝。

+1

我得到兩個變化,但從null - > bar,然後在你的JSFiddle例子中bar - > baz。 – Tom

+1

的確如此,但是 - 正如我在對@ ikram-shah答案的評論中所解釋的,問題似乎在polyfill上。 Chrome v54 +本身就實現了'customElements',所以不使用polyfill,並且該函數只被調用一次。 – romaintaz

回答

1

我回顧了你的jsfiddle,它實際上並沒有在按鈕點擊時被調用兩次,而是在<my-component id="compo" foo="bar"></my-component>被渲染時首先調用,因爲你設置的值爲foo;其次當你點擊按鈕。

您還可以調試它的jsfiddle,使用的開發工具,然後按Ctrl鍵++˚F查找和調試功能。

Screenshot

+0

謝謝。我已經在最新版本的Chrome上測試了我的JsFiddle,實際上這個調用只做了一次。在我的專業電腦上,我使用的是Chrome v53,它不執行customElements(在v54中添加),所以使用polyfill和** there **,調用兩次。所以問題在於polyfill! – romaintaz

相關問題