Skip to content

Instantly share code, notes, and snippets.

@robdodson
Created September 26, 2013 19:05
Show Gist options
  • Select an option

  • Save robdodson/6719017 to your computer and use it in GitHub Desktop.

Select an option

Save robdodson/6719017 to your computer and use it in GitHub Desktop.
polymer and native custom elements
<template id="chart-pie">
<style>
:host {
display: inline-block;
}
</style>
<canvas class="myChart" width="200" height="200"></canvas>
</template>
<script>
(function () {
var link = document.querySelector('link[href$="chart.html"');
var template = link.import.querySelector('#chart-pie');
// Make sure you extend an existing HTMLElement prototype
var ChartPieProto = Object.create(HTMLElement.prototype);
// Setup optional lifecycle callbacks: createdCallback,
// enteredDocumentCallback, leftDocumentCallback and
// attributeChangedCallback
ChartPieProto.createdCallback = function() {
// Create a ShadowDOM to hold our template content
var root = this.createShadowRoot();
var clone = template.content.cloneNode(true);
// Create the pie chart with Chart.js
var data = [
{
value: 30,
color:"#F38630"
},
{
value : 50,
color : "#E0E4CC"
},
{
value : 100,
color : "#69D2E7"
}
];
// Get the context of the canvas element we want to select
var ctx = clone.querySelector('.myChart').getContext('2d');
var myNewChart = new Chart(ctx).Pie(data);
// Add the template content + chart to our Shadow DOM
root.appendChild(clone);
};
// Including polymer.js causes this section to error because the imports run twice
// Only thing to do is to wrap it in a try/catch
try {
var ChartPie = document.register('chart-pie', { prototype: ChartPieProto });
} catch(e) {}
// Now that the element is registered it can be instantiated
// in a few ways:
// ex1: var chartPie = new ChartPie();
// ex2: var chartPie = document.createElement('chart-pie');
// ex3: <chart-pie></chart-pie>
}());
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment