如何将d3 v4与Polymer 2.0类一起使用?

时间:2017-03-31 01:39:18

标签: d3.js ecmascript-6 polymer es6-class polymer-2.x

d3.js(v4)如何与Polymer 2.0元素一起使用?
或者如何在已经扩展另一个类的类中使用库?

尝试创建聚合物d3元素,以利用聚合物的双向数据绑定和d3的语法和功能。这样数据可以绑定到聚合物属性并传递给d3.data()函数?

目前在类中声明d3返回undefined。该类是否需要使用d3作为参数进行实例化?它似乎适用于Polymer 1.0。另一种方法是在类之外创建一个函数并调用它,但它很难看。在课堂上使用d3会很不错。

或者有更好的清洁方法吗?

例如

<script src="../../bower_components/d3/d3.js"></script>
var d3 = d3; 
debugger; // hits this breakpoint first, and d3 is defined here and below 
<dom-module id="my-app">
  <template>
     <svg id="svg"></svg>
  </template>
  <script>
    class MyApp extends Polymer.Element {
      static get is() { return 'my-app'; }
      static get properties() {
        return {
          data: {
            type: Object,
            observer: '_dataChanged'
          }
        }
      }

      ready: {
        var d3 = d3;  // when it breaks here on the above breakpoint this is defined
        debugger;  // when it hits this breakpoint 2nd, d3 is undefined here and outside the class; what happened? how to scope it in?
      }

      _dataChanged(newValue, oldValue): {
        var circle = d3.select(this.$.svg).data(newValue).enter().append(circle);  //d3 undefined(! how to define?)
      }

    }
    window.customElements.define(MyApp.is, MyApp);
  </script>
</dom-module>

1 个答案:

答案 0 :(得分:1)

window.d3 is the way as you're loading the script in the global scope. You can load any external script asynchronously or synchronously.

To load it synchronously, just place the <script> tag in the <head>.

To load it asynchronously, you can add an load event listener to the <script> tag to do subsequent stuff when the load is completed.