Supriya Kale
Supriya Kale

Reputation: 845

What is Mixin and when to use it in the polymer?

I am quite new to Polymer framework and was checking if we can inherit from multiple classes in it, then I came across idea of Mixin. Still I have some confusions about it. I need good examples explaining idea of Composition, Multiple inheritance and role of Mixin to achieve it. I shall be grateful for the help.

Thanks

Upvotes: 1

Views: 1592

Answers (1)

Hyyan Abo Fakher
Hyyan Abo Fakher

Reputation: 3527

Mixins

A mixin is an abstract subclass; i.e. a subclass definition that may be applied to different superclasses to create a related family of modified classes. - Gilad Bracha and William Cook, Mixin-based Inheritance

In simpler words a class expression mixins let you share code between elements without adding a common superclass. In Polymer a mixin looks similar to a typical Polymer prototype and can define lifecycle callbacks, declared properties, default attributes, observers, and event listeners

Here is a simple example

SelectedMixin = function (superClass) {
return class extends superClass {

    static get properties() {
        return {
            isSelected: {
                type: Boolean,
                value: false,
                notify: true,
                observer: '_selectedChanged'
            }
        };
    }

    _selectedChanged(selected) { 
        // do something
    }

    getSelectedItems() {
        // do something
    }
   }
}


class MyElement1 extends SelectedMixin(Polymer.Element) { 

      hightligh(){
            const selected = this.getSelectedItems();
            // do something
      }
}

class MyElement2 extends SelectedMixin(Polymer.Element) { 

    sort(){
        const selected = this.getSelectedItems();
        // do something
    }
}

You can see that we reused the SelectedMixin with two elements without the need to duplicate the code in the two elements. If you have more than one mixin then you can use them like this

class MyElement extends MixinB(MixinA(Polymer.Element)) { ... }

You can read more about mixins from here

Polymer 2 supports also behaviors which work in a similar way to mixins.

Behaviors

Polymer 1 supported extending custom element prototypes with shared code modules called behaviors.

A simple example for behaviors can be written like this

<script>
SelectedBehavior = {

  properties: {
    isSelected: {
      type: Boolean,
      value: false,
      notify: true,
      observer: '_selectedChanged'
    }
  },

  _selectedChanged: function(selected) {
      // do something 
  },
};
<script>

<script>
  Polymer({
     is: 'my-element',
     behaviors: [SelectedBehavior]
  });
<script>

In Polymer 2 these behaviors cannot be used anymore like this. instead, you use them like this

<script>

  class MyElement extends Polymer.mixinBehaviors(
     [SelectedBehavior] , Polymer.Element) 
  {
      static get is() { return 'my-element' }
  }
</script>

Upvotes: 3

Related Questions