Search code examples
javascriptd3.jspolymerweb-component

Load JSON by URI using inline JSON in Polymer


I am making a d3.js map component with Polymer. The topology data needs to be loaded from a json file and since I don't want the component to be dependent on a URL/URI, I am using inline JSON instead of loading it using AJAX:

<polymer-element name="map-us">
    <template>


        <script id="topodata" type="application/json" src="data/us.json"></script> 

        /* ... more stuff ... */

    </template>


    <script>

        Polymer('map-us', {


            ready: function() {

                /* 
                This  works in regular HTML/JQuery:

                var x = JSON.parse($('#myJson').html());
                console.log(x.arcs);

                */

                var x = JSON.parse(this.$.topodata.html());
                console.log(x.arcs);

        });
    </script>
</polymer-element>

But obviously topdata element doesn't have the method html().

Is it the right thing to do? and how vulcanize deal with this?


Solution

  • There is no need to inline JSON file. Polymer's resolvePath function is useful here to make sure the relative path to JSON file is always correct regardless of where the component is included:

    this.topojsonURI = 'data/us.json';
    
    /* d3.json basically just makes the json call */
    
    d3.json(this.resolvePath(this.topojsonURI), function() {
      /* code rendering the map */
    }
    

    Info about resolvePath here.

    UPDATE (Polymer 1.0):

    The function name has been changed to resolveUrl: 1.0 API Docs