JavaScript Patterns 4.7 Init-Time Branching

When you know that a certain condition will not change throughout the life of the program, it makes sense to test the condition only once. Browser sniffing (or feature detection) is a typical example.

// BEFORE

var utils = {

    addListener : function(el, type, fn) {

        if ( typeof window.addEventListener === ‘function‘) {

            el.addEventListener(type, fn, false);

        } else if ( typeof document.attachEvent === ‘function‘) {// IE

            el.attachEvent(‘on‘ + type, fn);

        } else {// older browsers

            el[‘on‘ + type] = fn;

        }

    },

    removeListener : function(el, type, fn) {

        // pretty much the same...

    }
};

// AFTER

// the interface

var utils = {

    addListener : null,

    removeListener : null

};

// the implementation

if ( typeof window.addEventListener === ‘function‘) {

    utils.addListener = function(el, type, fn) {

        el.addEventListener(type, fn, false);

    };

    utils.removeListener = function(el, type, fn) {

        el.removeEventListener(type, fn, false);

    };

} else if ( typeof document.attachEvent === ‘function‘) {// IE

    utils.addListener = function(el, type, fn) {

        el.attachEvent(‘on‘ + type, fn);

    };

    utils.removeListener = function(el, type, fn) {

        el.detachEvent(‘on‘ + type, fn);

    };

} else {// older browsers

    utils.addListener = function(el, type, fn) {

        el[‘on‘ + type] = fn;

    };

    utils.removeListener = function(el, type, fn) {

        el[‘on‘ + type] = null;

    };

}

JavaScript Patterns 4.7 Init-Time Branching,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。