2014-10-20 101 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中收听更改。