JavaScriptで実装してて思ったこと_2

by opengl_8080

HTML

<div>
    姓名:
    苗字<input id="family-name" type="text" />
    名前<input id="first-name" type="text" />
</div>
<div>
    年齢:<input id="age" type="text" />
</div>
<div>
    性別:
    <label>
        男<input name="sex" type="radio" value="male" />
    </label>
    <label>
        女<input name="sex" type="radio" value="female" />
    </label>
</div>
<div>
    連絡先:
    <label>
        不要<input name="contact" type="radio" value="unnecessary" checked />
    </label>
    <label>
        必要<input name="contact" type="radio" value="necessary" />
    </label>
    メールアドレス:<input id="mail-address" type="text" disabled />
</div>
    
<button id="submit">送信</button>

CSS

div {
    margin-bottom: 10px;
}

input[type="text"] {
    width: 100px;
}

JavaScript

/* ======================================================= */
// プリミティブなクラス
/* ======================================================= */
// テキストボックス
function TextBox(options) {
    var opt = $.extend({}, options);
    
    var $textbox = $(opt.selector);
    
    this.is = function(predicate) {
        return predicate($textbox.val());
    };
    
    this.setEnable = function(enable) {
        var disabled = !enable;
        $textbox.attr('disabled', disabled);
    };
}

// ラジオボタン
function RadioButton(options) {
    var opt = $.extend({}, options);

    var $radio = $('[name="' + opt.name + '"]');

    this.change = function(callback) {
        $radio.change(function() {
            callback(getValue());
        });
    };
    
    /**
     * ラジオボタンが選択されているかどうかを確認する。
     * 引数が指定されている場合は、その値が選択されているかどうかを確認する。
     */
    this.isSelected = function(expected) {
        if (arguments.length === 0) {
            return getValue() ? true : false;
        } else {
            return getValue() === expected;
        }
    };
    
    this.isNotSelected = function() {
        return !this.isSelected();
    };
    
    function getValue() {
        return $('[name="' + opt.name + '"]:checked').val();
    }
}

// ボタン
function Button(options) {
    var opt = $.extend({}, options);
    
    var $button = $(opt.selector);
    
    this.click = function(callback) {
        $button.click(function() {
            callback();
        });
    };
}

/* ======================================================= */
// 入力項目クラス
/* ======================================================= */
// 姓名
function FullName(options) {
    var opt = $.extend({}, options);
    
    var familyName = new TextBox({selector: opt.familyNameSelector});
    var firstName  = new TextBox({selector: opt.firstNameSelector});
    
    this.validate = function() {
        ValidationUtil.isTrue(familyName.is(not(empty())), '苗字は必須入力です。');
        ValidationUtil.isTrue(firstName.is(not(empty())), '名前は必須入力です。');
   ...