如何在附加到 DOM 时在 Polymer 组件中触发回调?

How to trigger a callback in a Polymer component when it's been attached to the DOM?

我在将 jsPlumb 集成到 Polymer 组件中时遇到了麻烦,该组件旨在用作 Electron 包装应用程序中的插件。我使用的 Polymer 版本是 1.2.0,因为这是应用程序附带的版本。

jsPlumb 要求可拖动元素及其源和目标已安装到 DOM,但在触发 attached 时情况似乎并非如此。

我所做的是设置一个 simeout 以继续查询 DOM 直到组件被 "truly" 安装,然后继续初始化将 jsPlumb 的新实例传递到图中的节点这样他们就可以为每个输入和输出端口正确设置源和目标。

问题

我想知道是否有另一种方法 "wait" 仅使用 Polymer API 而不是超时来使组件可用于 jsPlumb?

<link rel="import" href="my-node.html">

<dom-module id="my-graph">
    <template>
        <div id="canvas">
            <template is="dom-repeat" items="{{nodes}}">
                <my-node></my-node>
            </template>
        </div>
    </template>

    <script>
        Polymer({
            is: "my-graph",
            properties: {
                nodes: {
                    type: Array,
                    value: function(){return [];}
                }
            },
            attached: function() {
                this._attachedDeferred();
            },
            _attachedDeferred: function() {
                // wait for the component to be attached
                if (!document.contains(this) || !this.offsetParent) {
                    setTimeout(function(){
                        this._attachedDeferred();
                    }.bind(this), 100);
                    return;
                }

                // ready to init jsPlumb
                this.instance = jsPlumb.getInstance({
                    Container: "canvas"
                });

                // init the graph nodes
                var nodes = [
                    {
                        pos: [0,0],
                        jsPlumb: this.instance; // the new instance of jsPlumb
                        inputs: {...},
                        outputs: {...}
                    }
                ];
                this.nodes = nodes;
            }
        });
    </script>
</dom-module>

我假设您正在尝试访问 <my-node> 个元素?

<template is="dom-repeat"> 异步创建其内容,因此 children 在 attached 期间尚不可用。 在访问它们之前,您需要监听 dom-change 事件。

查看 "Initialization timing for local DOM children" header 之后的 documentation