用于模板数据绑定的聚合物回调

Polymer callbacks for template data binding

本文关键字:聚合物 回调 数据绑定 用于      更新时间:2023-09-26

我有一个模板,比如:

<template id="container" repeat="{{ sheep, i in flock }}" is="auto-binding">
    <svg id="sheep{{i}}"></svg>
</template>

然后我异步加载数据,比如:

    // ...
    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));
}

但是当到达draw时,this.$['sheep'+i]还没有创建。

有没有回调可以用来检测DOM元素何时在模板绑定后插入?

[EDIT]使用auto-binding 时,必须使用模板元素作为模型,而不是this元素实例

[EDIT]经过进一步研究,发现template-bound事件在创建模板时只触发一次,而在更新模板时不会触发。一旦加载了数据,就会更新模型,然后同步调用draw函数。我怀疑当模型观察到变化时,模板会异步更新,从而在执行draw函数时使this.$.container.$['sheep'+i]不可用。我需要在模板完成节点更新后异步运行draw函数。

[EDIT]请参阅测试的jsfiddle代码

找到了!耶
你可以使用Polymer的辅助突变功能(或者香草突变观察者)

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

请注意,您需要监听元素的shadowRoot,而不是元素本身,因为明显的更改事件不会穿透阴影边界。一开始我没有注意到,但文档中指出,这只是为了倾听光域的变化。