zoukankan      html  css  js  c++  java
  • 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;
    
        };
    
    }

    References: 

    JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

  • 相关阅读:
    Assert.isTrue 用法
    P2967 [USACO09DEC]视频游戏的麻烦Video Game Troubles
    最近目标2333
    LibreOJ β Round #2」贪心只能过样例
    CF1062F Upgrading Cities 拓扑排序
    CF1108F MST Unification
    CF915D Almost Acyclic Graph 拓扑排序
    Swift日历控件Calendar
    README.md的markdown语法
    MAC打开App显示已损坏
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Init-Time-Branching.html
Copyright © 2011-2022 走看看