Reputation: 761
Browser: Dartium Version 34.0.1847.0 (258268)
I want to embed D3 inside Polymer.dart elements and I'm just beginning to sort out how Dart and JS interoperate. I started by creating a vanilla HTML page using HTML5/CSS3/JS from D3's introductory tutorial on how to make a bar chart to be sure my D3 implementation worked in Dartium.
I then moved the D3 code into a custom polymer element (shown below) and its companion dart source file (not shown). How do I instruct D3 to perform its selection inside the shadow DOM?
<!-- D3 code copied from: http://bost.ocks.org/mike/bar/ -->
<polymer-element name="dart-js">
<template>
<!-- D3 style -->
<style>
.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
</style>
<content>
<!-- D3 container -->
<div class="chart">inside dart-js shadow-root</div>
<!-- D3 JS -->
<script type="application/javascript">
console.log("inside content");
var data = [4, 8, 15, 16, 23, 42];
console.log("data: " + data); // data: 4,8,15,16,23,42
console.log("select: <" + d3.select(".chart") + ">"); // select: <>
// How do I instruct d3 to search inside the shadow DOM?
d3.select(".chart")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function (d) { return d * 10 + "px"; })
.text(function (d) { return d; })
</script>
</content>
</template>
<script type="application/dart;component=1" src="dart_js.dart"></script>
</polymer-element>
Upvotes: 3
Views: 1367
Reputation: 761
I wrapped the D3 JS fragment that prints the bar chart in a function and invoked it from Dart as follows:
dart-js.html
var x = function(elt) {
console.log('x');
d3.select(elt)
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function (d) { return d * 10 + "px"; })
.text(function (d) { return d; });
};
dart_js.dart
import 'package:polymer/polymer.dart';
import 'dart:js' as js;
@CustomTag('dart-js')
class DartJs extends PolymerElement {
/* Life cycle events */
// required -- constructor must call superclass
DartJs.created() : super.created() {
print("dart-js started");
}
@override void enteredView() {
super.enteredView();
print('dart_js entered');
js.context.callMethod('x', [shadowRoot.querySelector('.chart')]);
}
}
Upvotes: 1
Reputation: 658037
d3 can't find elements inside a shadowDOM but you look up the element in Dart and pass it to d3's select method.
something like this (not tested)
import 'dart:js' as js;
js.context['d3'].callMethod('select', [shadowRoot.querySelector('.chart')]);
more info about Dart-JS-interop: https://www.dartlang.org/articles/js-dart-interop/
Upvotes: 5