Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 设计模式(外观模式) #33

Open
wl05 opened this issue May 29, 2019 · 0 comments
Open

javascript 设计模式(外观模式) #33

wl05 opened this issue May 29, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented May 29, 2019

本系列文章来源于《Javascript设计模式》(张容铭版),做一个记录。

关于外观模式,其实就是对复杂接口进行封装来简化使用,或者对一些需要进行兼容的操作进行封装来简化使用。

1. 封装获取元素的方法库

// 元素获取
var A = {
    g: function (id) {
        return document.getElementById(id);
    },
    css: function (id, key, value) {
        return document.getElementById(id).style[key] = value;
    },
    attr: function (id, key, value) {
        document.getElementById(id)[key] = value;
    },
    html: function (id, html) {
        document.getElementById(id).innerHTML = html;
    },
    on: function (id, type, fn) {
        document.getElementById(id)['on' + type] = fn;
    }
}
A.css('box', 'background', 'red')

通过对dom操作对封装,我们简化了一系列的操作。

2. 兼容

我们在绑定事件的时候,不同浏览器中的实现方式是不一样的。因此我们可以通过外观模式对这些方法进行封装。

// 兼容
function addEvent(dom, type, fn) {
    // 对于支持DOM2级事件处理程序addEventListener方法的浏览器
    if (dom.addEventListener) {
        dom.addEventListener(type, fn, false);
    // 对于不支持addEventListener但支持attachEvent的浏览器
    } else if (dom.attachEvent) {
        dom.attachEvent('on' + type, fn);
    // 对于不支持addEventListener也不支持attachEvent,但支持on + '事件名'的浏览器。
    } else {
        dom['on' + type] = fn;
    }
}

var myInput = document.getElementById('myInput');
addEvent(myInput, 'click', function () {
    console.log('绑定事件')
})

通过这种方式我们以后在绑定事件的时候,就不用担心浏览器兼容的问题了。

我们再来看一个兼容性的例子

// 获取事件对象
var getEvent = function (event) {
    // 标准浏览器返回event,IE下window.event
    return event || window.event;
}
// 获取元素
var getTarget = function (event) {
    var event = getEvent(event);
    // 标准浏览器event.target,IE下event.srcElement
    return event.target || event.srcElement;
}
// 阻止默认行为
var preventDefault = function (event) {
    var event = getEvent(event);
    // 标准浏览器
    if (event.preventDefault) {
        event.preventDefault();
        // IE 浏览器
    } else {
        event.returnValue = false;
    }
}

document.onclick = function (e) {
    preventDefault(e);
    if (getTarget(e) !== document.getElementById('myInput')) {
        // ......
    }
}

通过一系列的封装我们简化了对兼容性的一系列判断。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant