Is it possible to share mixins across web components (and imports) in Polymer?

前端 未结 2 678
梦谈多话
梦谈多话 2021-02-06 03:32

As a follow up to How to extend multiple elements with Polymer and Polymer multiple inheritence/composition, based on their answers, I wonder if it\'s possible to share mixins a

相关标签:
2条回答
  • 2021-02-06 04:12

    To use a global-like component is the recommended way to go.
    make a <name-you-like> and use get/set to change it (also you can use attributes although they are only sad strings).

    from Polymer API guide you'll see working (good looking) examples like this:

     <polymer-element name="app-globals">
      <script>
      (function() {
        // these variables are shared by all instances of app-globals
        var firstName = 'John';
        var lastName = 'Smith';
    
        Polymer({
           ready: function() {
             // copy global values into instance properties
             this.firstName = firstName;
             this.lastName = lastName;
           }
        });
      })();
      </script>
    </polymer-element>
    

    And play with them using javascript es5 getters/setters such as in the above mentioned case would look like

     <polymer-element name="app-globals">
      <script>
      (function() {
        // these variables are shared by all instances of app-globals
        var firstName = 'Arnold';
        var lastName = 'Schwarzenegger';
    
        Polymer({
           ready: function() {
             // copy global values into instance properties
             this.firstName = firstName;
             this.lastName = lastName;
           },
           get fullTerminatorName() {
             return this.firstName + ' ' + this.lastName;
           }
        });
      })();
      </script>
    </polymer-element>
    

    I'll be back.

    0 讨论(0)
  • 2021-02-06 04:20

    This is now addressed by the Behaviors feature.

    Example:

    my-behavior.html:

    <script>
      MyBehavior = {
        properties: {},
        listeners: [],
        _myPrivateMethod: function(){}
        // etc.
      };
    </script>
    

    my-element.html:

    <link rel="import" href="my-behavior.html">
    
    <script>
      Polymer({
        is: 'my-element',
        behaviors: [MyBehavior]
      });
    </script>
    

    my-other-element.html:

    <link rel="import" href="my-behavior.html">
    
    <script>
      Polymer({
        is: 'my-other-element',
        behaviors: [MyBehavior]
      });
    </script>
    
    0 讨论(0)
提交回复
热议问题