【问题标题】:Insert multiple instances of a same widget into a page将同一小部件​​的多个实例插入页面
【发布时间】:2017-03-20 09:19:57
【问题描述】:

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

是否可以使用 shadow-dom 完成上述操作?我尝试了以下操作,但注意到小部件无法选择正确的 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>

【问题讨论】:

  • @Supersharp 渲染同一小部件​​的多个实例。
  • @Supersharp 我用更多代码更新了问题。我只使用 shadow-dom。

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


【解决方案1】:

这是一个重用模板以使用 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 以外的浏览器上实现的标准规范。将来会弃用旧版本。

使用&lt;slot&gt;获取light DOM的内容,插入到Shadow DOM中。

【讨论】:

  • 假设我有一个这样的模板,jsfiddle.net/4qu6jks3 我必须在其中执行一个脚本标签。尝试了这种方法stackoverflow.com/questions/40736326/…,但没有成功。
  • @udarakr 最好的方法是定义一个自定义元素:jsfiddle.net/woekreuc/2。否则,您将不得不从外部更新 shadow dom 的内容(或在插入 shadow dom 之前更新模板的克隆)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多