Search code examples
javascripthtmldata-bindingpolymerweb-component

Providing data to Polymer elements


I want to have a single source provide all of my data. A model if you will, and I want my elements to be able to utilize that data, but never change it (one way data-binding). How can I go about this? Should I add the data as a behavior?

I tried doing this in my document:

<script type="text/javascript" src="/data.js"></script> <!-- defines a global object named DATA -->
<my-element data="{{DATA}}"></my-element>

And this inside my-element.html

<dom-module id="my-element">
  <template></template>
  <script>
    Polymer({
      is: 'my-element',
      properties: {
        data: Object
      },
      ready: function () {
        console.log(this.data);
      }
    });
  </script>
</my-element>

but it doesn't seem to work, the value of this.data is literally "{{data}}".

I am looking for a better solution than wrapping the element declaration inside a dom-bind template


Solution

  • To use data binding, you either need to use it inside a polymer element, or inside a dom-bind element. See the explanation here. If you use dom-bind, it's only a case of using the js to set DATA to a property on the dom-bind template element, 'data' maybe, which would be little code.

    Essentially, you can't set a global and expect data binding to know about it. You need to either tell dom-bind about it, or the element about it, by setting a property on the element, perhaps using behaviour, as you suggested, or using Mowzer's approach.

    An example of using a behaviour would be:

    <link rel="import" href="databehaviour.html"> 
    <link rel="import" href="bower_components/polymer/polymer.html">
    
    <dom-module id="an-ele">
    
        <style>
        </style>
        <template>
            <div>{{data.sth}}</div>
        </template>
        <script>
            Polymer({
                is: "an-ele",
                behaviors: [DataBehaviour]
            });
        </script>
    
    </dom-module>
    

    With the behaviour being:

    <script>
        DataBehaviour = {
            ready: function() {
                this.data = {'sth':'A thing! A glorious thing!'};
            }
        }
    </script>
    

    But in your case, this.data would be set to your DATA global.