If you're working in pure JavaScript without the use of frameworks like React, Angular, or jQuery, consider utilizing the existing Observer Pattern within DOM elements to handle updates triggered by changes.
Here's an abstraction:
// Define the AbstractControl class.
var AbstractControl = function() {
}
// Virtual methods.
AbstractControl.prototype.isValid = function() {
throw new Error('Not implemented.')
}
AbstractControl.prototype.paintGreen = function() {
// Handling valid scenario.
throw new Error('Not implemented.')
}
AbstractControl.prototype.paintRed = function() {
// Handling invalid scenario.
throw new Error('Not implemented.')
}
// The update function checks the control's validity and triggers appropriate actions.
AbstractControl.prototype.update = function() {
if (this.isValid()) {
this.paintGreen();
} else {
this.paintRed();
}
}
Let's create a concrete control class as an example:
// Class representing an email input field, taking a DOM element.
var EmailField = function(element) {
AbstractControl.call(this, AbstractControl);
this.element = element;
// Listens for change events on the element and updates its status.
this.element.addEventListener("change", this.update.bind(this));
}
// Inherit from AbstractControl.
EmailField.prototype = Object.create(AbstractControl.prototype);
EmailField.prototype.constructor = EmailField;
// Implement virtual methods.
EmailField.prototype.isValid = function() {
return this.element.value.indexOf("@") >= 0;
}
EmailField.prototype.paintGreen = function() {
alert("Email is correct. Proceed.")
}
EmailField.prototype.paintRed = function() {
alert("Invalid email! Please correct.")
}
Usage example:
new EmailField(document.getElementById("emailfield"));
An alert will pop up on every change based on the content of the field. You could modify the behavior to visually indicate the status instead of using alerts.
JSFiddle demo: https://jsfiddle.net/surj64vy/ (demonstrating real-time updates and visual cues instead of alerts)