将状态从控件发送到框架

Send status from controls to framework

本文关键字:框架 控件 状态      更新时间:2023-09-26

我有UI控件继承自抽象控件,在抽象控件中我有一个方法每个控件都应该扩展它叫做isValid返回真/假我需要(作为框架)要知道是否将其标记为红色(非有效情况),在这种情况下我应该使用一个设计模式来帮助我解决这个问题,或者我应该使用哪种方法?

如果你是在纯Javascript中开发(即没有React或Angular或jQuery),我会使用现有的DOM元素中可用的Observer Pattern来更新更改。

抽象部分:

// Create the basic AbstractControl class.
var AbstractControl = function() {
}
// Virtual methods.
AbstractControl.prototype.isValid = function() {
    throw new Error('Not implemented.')
}
AbstractControl.prototype.paintGreen = function() {
    // Valid case.
    throw new Error('Not implemented.')
}
AbstractControl.prototype.paintRed = function() {
    // Invalid case.
    throw new Error('Not implemented.')
}
// Function Update verifies the validity of the control and calls
// the valid or invalid case accordingly.
AbstractControl.prototype.update = function() {
    if (this.isValid()) {
        this.paintGreen();
    } else {
        this.paintRed();
    }
}

和一个具体的控制类示例:

// Class for an email input text field, receives a DOM element.
var EmailField = function(element) {
    AbstractControl.call(this, AbstractControl);
    this.element = element;
    // Listens for change events on the element and updates
    // the valid/invalid status.
    this.element.addEventListener("change", this.update.bind(this));
}
// Setup inheritance.
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 correct. Proceed.")
}
EmailField.prototype.paintRed = function() {
    alert("Email Incorrect! May not proceed.")
}
最终用途:

new EmailField(document.getElementById("emailfield"));

根据字段内容的变化,它将alert。您可以更改alert来代替元素的颜色(如函数名所示),或显示一些图标或工具提示。

JSFiddle: https://jsfiddle.net/surj64vy/(使用更多事件实时捕获更改,并绘制字段而不是发出警报)