将同一窗口小部件的多个实例插入页面

时间:2017-03-20 09:19:58

标签: javascript html css web-component shadow-dom

在指向特定数据源/ API之后,我有一个呈现条形图(HTML / CSS / JavaScript)的小部件。有一个配置参数可以更改数据源/ API,因此我可以拥有同一个小部件的多个实例。

是否可以使用shadow-dom进行上述操作?我尝试了以下但是注意到widget无法选择正确的div元素来执行渲染部分。

        var host = document.querySelector("#" + gadgetContainer.getAttribute("data-grid-id"));
        var root = host.createShadowRoot();

        var template = document.createElement('template');
        template.innerHTML = gadgetContainer.outerHTML; 
        root.appendChild(document.importNode(template.content, true));

以下是执行窗口小部件渲染的JavaScript逻辑,为了清晰起见,我删除了数据集和配置。

(function () {
    "use strict";
    //dataset used to plot charts
    var dataTable = {}, //REMOVED
        width = document.querySelector('*::shadow #bar').offsetWidth,
        height = 270,   //canvas height
        config = {}; //REMOVED
    widget.renderer.setWidgetName("bar-chart", "BAR CHART");

    chartLib.plot("*::shadow #bar",config, dataTable);
}());

以下是简单的HTML div,此页面中包含所有必需的样式表和脚本。

<div id="bar" class="bar"></div>

1 个答案:

答案 0 :(得分:2)

以下是重用模板以使用Shadow DOM创建同一小部件​​的2个实例的最小示例:

var template = document.querySelector( 'template' )

target1.attachShadow( { mode: 'open' } )
       .appendChild( template.content.cloneNode( true ) )
       
target2.attachShadow( { mode: 'open' } )
       .appendChild( template.content.cloneNode( true ) )
<template>
  <style>
    :host { display: inline-block; width:100px; height:50px ; border: 1px solid gray; }
    header { color: blue; font-size:15px; font-weight: bold; }
    section { color: gray; font-size:12px ; }
  </style>
  <header>
     Widget <slot name="number"></slot>
  </header>
  <section>
     Content
  </section>
</template>

<div id="target1"><span slot="number">1</span></div>

<div id="target2"><span slot="number">2</span></div>

请注意,您应该使用Shadow DOM“v1”,而attachShadow()代替createShadowRoot(),因为它是将在其他Chrome浏览器上实施的标准规范。旧版本将来会被弃用。

使用<slot>获取light DOM的内容并将其插入Shadow DOM。