2014-10-20 82 views
1

我有這樣一個模板聚合物回調模板數據綁定

// ... 
    ajaxHandler: function(e){ 
     // this.flock = e.detail.response; 
     this.$.container.flock = e.detail.response; 
     draw.call(this); 
    } 
}); 

function draw(){ 
    // this.flock.forEach(function(sheep,i){ 
    // this.$['sheep'+i].append(document.createElement("circle")); 
    // }.bind(this)); 
    this.$.container.flock.forEach(function(sheep,i){ 
     this.$.container.$['sheep'+i].append(document.createElement("circle")); 
    }.bind(this)); 
} 

但是當達到drawthis.$['sheep'+i]不會一直尚未創建。

有沒有回調我可以用來檢測何時DOM模板綁定後插入DOM元素?

[編輯]必須使用模板元素的模型,而不是this元素實例使用auto-binding

[編輯]時做更多的研究後,事實證明,在template-bound事件只觸發一次當模板創建時,但不是更新時。一旦數據被加載,模型就會被更新,然後繪圖函數被同步調用。我懷疑該模板在模型觀察到更改時異步更新,使this.$.container.$['sheep'+i]在繪圖函數執行時不可用。我需要繪圖函數在模板完成更新節點後異步運行。

[編輯]jsfiddle的代碼測試

回答

0

找到了!好極了!
您可以使用聚合物的助手onMutation功能(或者香草MutationObserver

ready: function(){ 
    this.onMutation(this.shadowRoot, function(observer, mutations){ 
    console.log('template should have updated'); 
    }); 
}, 

請注意,你需要的元素的shadowRoot而不是元素本身聆聽顯然change events don't pierce shadow boundaries。我一開始並沒有注意到,但it is stated in the docs它只適用於在light dom中收聽更改。