Search code examples
polymerpolymer-2.x

Polymer: How to use imported function in computed binding


I'd like to use a shared function for computed bindings in different custom elements. Is this possible?

No matter how I import the shared function, I get console errors:

method `formatAmount` not defined

The computed binding is something like:

<span>[[formatAmount(amount)]]</span>

I've tried using a tag above the element. I've tried inside the element. And I've tried in index.html.

Do all computed binding methods need to be defined in the custom element and can't be shared? Do I have to use a mixin?

UPDATE: I've created an ugly work around where I define a private method on my custom element that calls the shared method. Then the private method is used in the computed binding. This is ugly because of the extra boilerplate.

...
<script src="format-amount.js"></script>

<dom-module id="my-foo">
  <template>
    ...[[_formatAmount(amount)]]...
  </template>
  <script>
    class MyFoo extends Polymer.Element {
      ...
      _formatAmount(amount) {
        return formatAmount(amount); // Defined in format-amount.js.
      }
    }
  </script>
</dom-module>

Solution

  • This is similar question to what I have asked few months ago.

    You can use mixin. A mixin is simply a function that takes a class and returns a subclass. If you want to learn more click here.

    For your problem define mixin in separate html file say - my-mixin.html:

    const MyMixin = (superClass) => class extends superClass {
    
        constructor() {
          super();          
        }
    
        formatAmount(amount) {
          //function contents  
        }
    
    }
    

    And then in your element import and add mixin:

    <link rel="import" href="my-mixin.html">

    class MyFoo extends MyMixin(Polymer.Element)

    Then you can simply call the function from your element:

    <template>
      ...[[formatAmount(amount)]]...
    </template>
    

    To access the function in script use super.formatAmount(amount).