码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 4.7 Init-Time Branching

时间:2014-06-18 22:35:12      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   color   

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,布布扣,bubuko.com

JavaScript Patterns 4.7 Init-Time Branching

标签:style   class   blog   code   java   color   

原文地址:http://www.cnblogs.com/haokaibo/p/Init-Time-Branching.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!