Search code examples
polymerpolymer-2.x

Global functions in Polymer 2.0


Is there any way to declare a global function in Polymer 2.0 that can be used in other components? I have a moment.html file for using moment.js in the project:

<script src="../bower_components/moment/moment.js"></script>

In the same file I also declare a function instead of declaring it in every single component where I want to use it:

<script>
  function format(date) {
    return moment(date).format('dddd, D MMMM YYYY');
  }
</script>

The moment object is available after importing the file but when I try to call the format function it gives me the warning method 'format' not defined. How can I make the function publicly available?

Edit: I can call the format function from within the script tags of another component, but I cannot access it from within a template, i.e. with:

<strong>[[format(event.date)]]</strong>

I want to render the result from the function on the page, not access it programmatically.


Solution

  • I think, for your task, the best documentation is Monica Dinculescu's own cheat sheet.

    https://meowni.ca/posts/polymer-2-cheatsheet/#defining-a-mixin

    She's a Polymer developer. Below is me copy pasting from the link. It's the extends MyMixin(Polymer.Element) that does the magic.


    Defining a class expression mixin to share implementation between different elements:

    <script>
      MyMixin = function(superClass) {
        return class extends superClass {
          // Code that you want common to elements.
          // If you're going to override a lifecycle method, remember that a) you
          // might need to call super but b) it might not exist
          connectedCallback() {
            if (super.connectedCallback) {
              super.connectedCallback();
            }
            /* ... */
          }
        }
      }
    </script>
    

    Using the mixin in an element definition:

    <dom-module id="element-name">
      <template><!-- ... --></template>
      <script>
        // This could also be a sequence:
        //class MyElement extends AnotherMixin(MyMixin(Polymer.Element)) { … }
        class MyElement extends MyMixin(Polymer.Element) {
          static get is() { return 'element-name' }
          /* ... */
        }
        customElements.define(MyElement.is, MyElement);
      </script>
    </dom-module>