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.
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:
Mixin:
myElemenet.changeLanguage('de')
, ...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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With