@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
37 lines (36 loc) • 1.27 kB
JavaScript
import { BaseController } from "@stimulus-library/utilities";
import { installClassMethods, useEventListener } from "@stimulus-library/mixins";
export class WordCountController extends BaseController {
connect() {
installClassMethods(this);
this._updateWordCount();
useEventListener(this, this.inputTarget, "input", this._updateWordCount);
}
_updateWordCount() {
let wordCount = 0;
const textAreaValue = this.inputTarget.value;
const matches = textAreaValue.match(/\S+/g);
wordCount = (matches && matches.length) || 0;
this.outputTarget.innerText = wordCount.toString();
if (this._isValidCount(wordCount)) {
this.removeErrorClasses(this.outputTarget);
}
else {
this.addErrorClasses(this.outputTarget);
}
}
_isValidCount(count) {
let min = 0;
let max = 99999;
if (this.hasMinValue) {
min = this.minValue;
}
if (this.hasMaxValue) {
max = this.maxValue;
}
return count >= min && count <= max;
}
}
WordCountController.targets = ["input", "output"];
WordCountController.values = { min: Number, max: Number };
WordCountController.classes = ["error"];