Mixins as utility library in Polymer 2.0
Asked Answered
C

1

7

I am working in web application project which is made in Polymer 2.0, All Custom elements extends some Mixins. Some of those Mixins just provide utility functions to custom elements just like Date Time Utility functions or any Math related functions. My question is whether to use mixins & extends them to custom elements or just wrap them in plain java-script file and load that java-script file on index.html or entry point of application and use as global scope just like we use lodashjs or underscore.js.

The problem i find with Mixins is it always get applied to prototype chain of each custom element class object, So i end up those same utility methods with each custom element of my application.

Please suggest me best approach for Utilities in Polymer related apps.

Charyl answered 17/3, 2018 at 14:46 Comment(2)
+1 in .net and java methods such as these are placed in static classes i.e. they are not instance dependent.Paragon
See softwareengineering.stackexchange.com/questions/123342/…Secondbest
S
3

That is a rather tough question to answer properly... as the real answer is just "both are valid solutions - it depends on your use case". Which I guess is not helping too much. So let's give you some context.

For real utilities, it is probably best to put them in a class as a static function.

class MathHelper {
  static addOne(value) {
    return value + 1;
  }
}

class ElOne extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `5 + 1 = ${MathHelper.addOne(5)}`;
  }
}

customElements.define('el-one', ElOne);
<el-one></el-one>

Mixins, on the other hand, can serve a similar need but should be more "connected" to the Element they are used on. (Sorry for the terrible example but from the top of my head I could not come up with something better)

const MathMixin = superclass => class extends superclass {
  addOneTo(prop) {
    this[prop] += 1;
  }
}

class ElTwo extends MathMixin(HTMLElement) {

  constructor() {
    super();
    this.number = 5;
  }
  
  connectedCallback() {
    this.addOneTo('number');
    this.innerHTML = `5 + 1 = ${this.number}`;
  }
  
}

customElements.define('el-two', ElTwo);
<el-two></el-two>

Conclusion:

Class:

  • if possible use it
  • maybe even use static functions
  • it's easier to test and to maintain

Mixin:

  • if you need to enhance another class e.g. to allow myElemenet.changeLanguage('de'), ...
  • if you need any other state of the class

I hope this clears it up at least a bit. If you have more concrete examples what needs to be implemented we could propose a recommended way of implementation.

Sedlik answered 22/3, 2018 at 23:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.