简体   繁体   English

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

[英]Polymer callbacks for template data binding

I have a template like: 我有一个类似的模板:

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

then I load data asynchronously like: 然后我像这样异步加载数据:

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

But by the time draw is reached, this.$['sheep'+i] won't have been created yet. 但是到draw的时间, this.$['sheep'+i]尚未创建。

Is there a callback I can use to detect when the DOM elements have been inserted following a template binding? 是否有回调可用于检测在模板绑定后何时插入DOM元素?

[EDIT] Have to use the template element as model instead of the this element instance when using auto-binding [编辑]使用auto-binding时,必须将模板元素用作模型,而不是this元素实例

[EDIT] After doing more research it turns out that the template-bound event is only fired once when the template is created, but not when it is updated. [编辑]经过更多研究,结果发现template-bound事件在创建模板时仅触发一次,而在更新模板时不触发。 Once the data is loaded, the model is updated and the draw function gets called synchronously afterward. 加载数据后,将更新模型并随后同步调用draw函数。 I suspect the template updates asynchronously when the model observes a change, making this.$.container.$['sheep'+i] unavailable at the time the draw function will execute. 我怀疑当模型观察到更改时模板会异步更新,从而在执行绘图功能时使this.$.container.$['sheep'+i]不可用。 I need the draw function to be run asynchronously, after the template has finished updating its nodes. 在模板完成更新其节点之后,我需要draw函数异步运行。

[EDIT] See jsfiddle with code for testing [编辑]参见jsfiddle和代码进行测试

Found it! 找到了! Yay! 好极了!
You can use Polymer's helper onMutation function (or perhaps vanilla MutationObserver ) 您可以使用Polymer的助手onMutation函数(或者可以使用Vanilla MutationObserver

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

Note that you need to listen on the element's shadowRoot and not the element itself as apparently change events don't pierce shadow boundaries . 请注意,您需要侦听元素的shadowRoot而不是元素本身,因为显然更改事件不会穿透阴影边界 I didn't notice at first but it is stated in the docs that it's only for listening changes in the light dom . 起初我没有注意到,但是在文档中指出它仅用于监听light dom中的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM