2017-03-20 117 views
1

我有一個小部件,它指向特定的數據源/ 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> 
+0

@Supersharp渲染同一窗口小部件的多個實例。 – udarakr

+0

@Supersharp我用更多的代碼更新了這個問題。我只使用影子。 – udarakr

回答

2

下面是一個模板的重複使用的小例子,以創建同一控件的兩個實例與陰影DOM:

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>

請注意,您應該使用影子DOM 「v1」,attachShadow()而不是createShadowRoot(),因爲它是在其他瀏覽器上實現的標準規範。舊版本將在未來被棄用。

使用<slot>來獲取光DOM的內容並將其插入到Shadow DOM中。

+0

假設我有一個這樣的模板,https://jsfiddle.net/4qu6jks3/,我必須執行腳本標記。試過這種方法http://stackoverflow.com/questions/40736326/javascript-not-executing-inside-shadow-dom沒有運氣。 – udarakr

+2

@udarakr最好的方法是定義一個自定義元素:jsfiddle.net/woekreuc/2。否則你將不得不從外部更新影子dom的內容(或者在插入影子dom之前更新模板的克隆) – Supersharp

相關問題