将状态从控件发送到框​​架

5 javascript oop design-patterns

我是从抽象控件继承的UI控件,在抽象控件中,每个控件都应该扩展的方法,它被称为isValid,返回true/false,我需要(作为框架)知道是否将它标记为红色(无效的情况),在这种情况下我应该使用一种设计模式来帮助我使用这种方法或应该使用哪种方法?

Bop*_*reH 3

如果您使用纯 Javascript(即没有 React、Angular 或 jQuery)进行开发,我将使用 DOM 元素中现有的观察者模式来更新更改。

摘要部分:

// 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

以及一个具体的控制类示例:

// 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.")
}
Run Code Online (Sandbox Code Playgroud)

最终用途:

new EmailField(document.getElementById("emailfield"));
Run Code Online (Sandbox Code Playgroud)

并且它会alert根据字段内容进行每次更改。您可以更改alert来代替元素的颜色(如函数名称所示),或显示一些图标或工具提示。

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