DEV Community

Cover image for Using JavaScript Mixins The Good Parts
Thomas Allmer for Open Web Components

Posted on

Using JavaScript Mixins The Good Parts

Before we can start using something we need to understand what it is and what we can achieve with it.

What is a Mixin?

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.

Let's take for example Logging. Imagine you have 3 Pages

  • Red
  • Green
  • Blue
              +----------+
              |   Page   |
              +----------+
                |  |  |
     +----------+  |  +-----------+
     |             |              |
+---------+ +-----------+ +----------+
| PageRed | | PageGreen | | PageBlue |
+----+----+ +-----------+ +----------+

class Page {}
class PageRed extends Page {}
class PageGreen extends Page {}
class PageBlue extends Page {}

Now we want to log whenever someone goes on Page Red.
To achieve that we extend Page Red and make a Logged Page Red.

              +----------+
              |   Page   |
              +-+--+--+--+
                |  |  |
     +----------+  |  +-----------+
     |             |              |
+----+----+  +-----+-----+  +-----+----+
| PageRed |  | PageGreen |  | PageBlue |
+----+----+  +-----------+  +----------+
     |
+----+----+
| Logged  |
| PageRed |
+---------+
class Page {}
class PageRed extends Page {}
class PageGreen extends Page {}
class PageBlue extends Page {}
class LoggedPagRed extends PageRed {}

If we want to start logging for PageGreen we have an issue:

  • we can't put the logic in Page as Blue should not be logged
  • we can't reuse the logic in Logged PageGreen as we can not extend from 2 sources (even if we could it would mean conflicting info in Red and Green)

What we can do is put it in an "external" place and write it so it can be "mixed in".

               +----------+                +----------+
               |   Page   |                | Logging* |
               +-+--+--+--+                +----------+
                 |  |  |
      +----------+  |  +-----------+
      |             |              |
+-----+----+  +-----+-----+  +-----+----+
| PageRed  |  | PageGreen |  | PageBlue |
|  with    |  |   with    |  +----------+
| Logging* |  |  Logging* |
+----------+  +-----------+
// defining the Mixin
export const LoggingMixin = superclass =>
  class LoggingMixin extends superclass {
    // logging logic
  };

class Page {}
// applying a Mixin
class PageRed extends LoggingMixin(Page) {}
class PageGreen extends LoggingMixin(Page) {}
class PageBlue extends Page {}

With that approach we can extract logic into a separate code piece we can use where needed.

For a more in-depth technical explanation please read Real Mixins with JavaScript Classes.

Why is Deduping of Mixins Necessary?

We now want all logging to the Red, Green, and Blue pages.
Easy enough - as we can now apply the LoggingMixin on the Page itself.

               +----------+               +----------+
               |   Page   |               | Logging* |
               |   with   |               +----------+
               | Logging* |
               +-+--+--+--+
                 |  |  |
      +----------+  |  +-----------+
      |             |              |
+-----+----+  +-----+-----+  +-----+----+
| PageRed  |  | PageGreen |  | PageBlue |
+----------+  |   with    |  +----------+
              |  Logging* |
              +-----------+

However, Team Green was eager to launch, so they already applied LoggingMixin to their Page class. When we apply it to the base Page class, Mixin is now applied twice 😱
Suddenly, the Green page will print each log twice - not what we originally had in mind.

What we need to do is make sure that each Mixin is attached only once even if we try to apply it multiple times.

Generally, the more generic a mixin is, the higher the chance becomes that is gets applied more than once. As a mixin author, you can't control how it is used, and can't always predict it. So as a safety measure it is always recommended to create deduping mixins.

npm i @open-wc/dedupe-mixin
import { dedupeMixin } from '@open-wc/dedupe-mixin';

export const MyMixin = dedupeMixin(
  superclass =>
    class MyMixin extends superclass {
      // your mixin code goes here
    },
);

You can see exactly this situation in the demo.

By applying dedupeMixin to the mixin function, before we export it, we can be sure that our mixin class will only take effect once, even if it is mixed into multiple base classes in the inheritance chain.

  • no-dedupe "fails" by logging Green two times
  • with-dedupe "succeeds" by logging Green one time as well

You can check the source code for both on github.

Nested examples

You may think that the above example is too simple and can be solved by aligning on when to do changes.
However, in most real-life scenarios the situation is much more complicated 🙈
Mixins can be extended and just because you import a class it does not mean that this class has some Mixins pre-applied.

Consider this example:

               +----------+               +----------+      +----------+
               |   Page   |               | Logging* |      | Feature  |
               |   with   |               +----+-----+      |   with   |
               | Logging* |                    |            | Metrics* |
               +-+--+--+--+               +----+-----+      +----+--+--+
                 |  |  |                  | Metrics* |           |  |
      +----------+  |  +-----------+      +----------+           |  +------
      |             |              |                             |
+-----+----+  +-----+-----+  +-----+----+                 +------+-------+
| PageRed  |  | PageGreen |  | PageBlue |                 | WaterFeature |
+----------+  +-----------+  |   with   |                 +--------------+
                             | Metrics* |
                             +----------+
  • Pages generally only need Logging
  • There is however also more advanced Metrics System which extends Logging
  • Metrics was separately developed for Features
  • When we now want to get the same Metrics on Page Blue we get duplicate logging without consciously applying logging even once (we do class PageBlue extends MetricsMixin(Page) {})
  • Only deduping can help in these scenarios

When NOT to use a Mixin

You may think now "dam that is powerful" and you are right. Should we use it now for everything? Hell, no.

Only use it if you absolutely need access to the instance itself. Here are some bad examples when NOT to use a Mixin.

I want to do if (this.isIE11()) { // ... }

For any "pure" function it is better to keep it outside of the class/prototype. e.g. better write it like so

import { isIE11 } from './helpers.js';

if (isIE11()) {}

I want to have a special this.addEventListener()

Firstly overriding built-in functions can be really dangerous. When inside your class and when you need to make a very specific use-case happen then it might be ok. However, if that magically happens while using a Mixin it can be very confusing.

Better to have these as an extra function which can pass on this. That way people can opt these special features without "polluting" their prototype chain.

import { specialAddEventListener } from './helpers.js';

specialAddEventListener(this, 'click', () => console.log('clicked'));

Secondly all properties/methods are global to the class/prototype. That means if two mixins use the same name it will clash. Therefore make sure to definitely use specific names for private/protected methods and make sure if you use common names that it is clear from the mixin name/docs.

When to use a Mixin

If you need to have access to the class instance itself. Meaning if every instance may have a different setting.

A valid example could be for example a LocalizeMixin which enables you to set myEl.locale = 'de-DE';. In this case, the Mixin needs to provide and react to this property.

import { dedupeMixin } from '@open-wc/dedupe-mixin';

export const LocalizeMixin = dedupeMixin(
  superclass =>
    class LocalizeMixin extends superclass {
      // this assumes a Mixin for LitElement
      static get properties() {
        return {
          locale: { type: String }
        };
      }

      updated(changedProperties) {
        super.updated(changedProperties);
        if (changedProperties.has('locale')) {
          // react to locale change
        }
      }
    },
);

What we have learned

With Mixins you can bring shared logic into multiple classes. It is a very powerful tool - and with that power comes responsibility. Be sure to use it responsibly and to dedupe your mixins.

Notes

Ascii Graphics made with AsciiFlow
Photo by Vania Shows on Unsplash

Top comments (0)