灏天阁

装饰者模式

· Yin灏
/**
 * 装饰者模式
 * 在不改变原对象的基础上,通过对其进行包装拓展(添加属性和方法)使原有对象可满足用户的更复杂需求。
 */

// 装饰者
var decorator = function (input, fn) {
    // 获取事件源
    var input = document.getElementById(input);
    // 若事件源已经绑定事件
    if (typeof input.onclick === 'function') {
        // 缓存事件源原有的回调函数
        var oldClickFn = input.onclick;
        // 为事件源定义新的事件
        input.onclick = function () {
            oldClickFn();
            fn();
        }
    } else {
        input.onclick = fn;
    }
}

/**
 * 为输入框添砖加瓦
 */
// 电话输入框功能装饰
decorator('tel_input', function () {
    document.getElementById('tel_demo_text').style.display = 'none';
});
// 姓名输入框功能装饰
decorator('name_input', function () {
    document.getElementById('name_demo_text').style.display = 'none';
});
// 地址输入框功能装饰
decorator('address_input', function () {
    document.getElementById('address_demo_text').style.display = 'none';
});

- Book Lists -