JavaScript 디자인 모드 - 메소드의 체인 호출

13259 단어
  • 방법의 체인 호출
  • 호출 체인의 구조
  • 방법 체인 호출을 지원하는 자바스크립트 라이브러리
  • 설계
  • 소결

  • 방법의 체인 호출


    체인 호출은 사실 일종의 문법 수일 뿐이다. 이것은 너로 하여금 초기 조작을 다시 사용함으로써 소량의 코드로 복잡한 조작을 표현하는 목적을 달성하게 할 수 있다.
    이 기술은 다음 두 부분으로 구성됩니다.
  • 코드 HTML 요소를 만드는 객체의 플랜트
  • 및 이 HTML 요소에 대한 일부 조작 방법
  • 호출 체인 구조


    $함수, 일반적으로 HTML 요소나 HTML 요소의 집합을 되돌려줍니다. 예를 들어:
    function $(){
        var elements = [];
        for(var i = 0, len = arguments.length; i < len; ++i){
            var element = arguments[i];
            if(typeof element === "string"){
                element = document.getElementById(element);
            }
            if(arguments.length === 1){
                return element;
            }
            elements.push(element);
        }
    
        return elements;
    }

    그러나 이 함수를 하나의 구조기로 바꾸어 그 원소를 하나의 실례 속성에 수조로 저장하고 구조기 함수에 정의된prototype 속성이 대상을 가리키는 모든 방법을 호출 방법으로 사용된 실례의 인용으로 되돌려주면 체인 호출을 할 수 있는 능력을 가지게 된다.
    우선 이 $함수를 공장 방법으로 변경합니다. 체인 호출을 지원하는 대상을 만듭니다.이 함수는 우리가 원래와 같은 공공 인터페이스를 사용할 수 있도록 원소수 그룹 형식의 매개 변수를 받아들일 수 있어야 한다.
    (function(){
        //         
        function _$(els){
            this.elements = [];
            for(var i = 0, len = els.length; i < len; i++){
                var element = els[i];
                if(typeof element === "string"){
                    element = document.getElementById(element);
                }
                this.elements.push(element);
            }
        }
        //         
        window.$ = function(){
            return new _$(arguments);
        }
    })();

    모든 대상은 원형 대상의 속성과 방법을 계승하기 때문에 우리는 원형 대상에 정의된 몇 가지 방법을 호출된 실례 대상의 인용으로 되돌려보낼 수 있다. 그러면 그 방법에 대해 체인식 호출을 실현할 수 있다.이 점을 잘 생각해서 지금 바로 $이 사설 구조 함수의 prototype 대상에 방법을 추가하여 체인 호출을 실현합니다.
    (function(){
        function _$(els){
            this.elements = [];
            for(var i = 0, len = els.length; i < len; i++){
                var element = els[i];
                if(typeof element === "string"){
                    element = document.getElementById(element);
                }
                this.elements.push(element);
            }
        }
    
        _$.prototype = {
            each : function(fn){
                for(var i = 0, len = this.elements.length; i < len; i++){
                    fn.call(this, this.elements[i]);
                }
                return this;
            },
            setStyle : function(prop, val){
                this.each(function(el){
                    el.style[prop] = val;
                });
                return this;
            },
            show : function(){
                var that = this;
                this.each(function(el){
                    that.setStyle("display", "block");
                });
                return this;
            },
            addEvent : function(type, fn){
                var add = function(el){
                    if(window.addEventListener){
                        el.addEventlistener(type, fn, false);
                    } else if(window.attachEvent){
                        el.attachEvent("on" + type, fn);
                    }
                };
                this.each(function(el){
                    add(el);
                });
                return this;
            }
        };
    
        window.$ = function(){
            return new _$(arguments);
        };
    })();

    메소드 체인 호출을 지원하는 JavaScript 라이브러리 설계


    그 사적인 $에구조 함수를 확충하여 이 물건들을 모두 포함시키면 그 위조 코드는 대체로 다음과 같다.
    //                
    Function.prototype.method = function(name, fn){
        this.prototype[name] = fn;
        return this;
    };
    (function(){
        function _$(els){
            ...
        }
    
        /*
          Events
          * addEvent
          * getEvent
         */
         _$.method("addEvent", function(type, fn){
            // ...
        }).method("getEvent", function(type, fn){
            // ...
        })
    
        /*
          DOM
          * addClass
          * removeClass
          * replaceClass
          * hasClass
          * getStyle
          * setStyle
         */
    
        .method("addClass", function(className){
            // ...  
        }).method("removeClass", function(className){
            // ...
        }).method("replaceClass", function(oldClass, newClass){
            // ...
        }).method("hasClass", function(className){
            // ...
        }).method("getStyle", function(){
            // ...
        }).method("setStyle", function(){
            // ...
        })
    
        /*
         Ajax
        */
        .method("load", function(url, method){
            // ...
        });
    
        window.$ = function(){
            return new _$(arguments);
        };
    })();

    만약 어떤 API가 $함수를 정의했다면, 이 라이브러리는 덮어쓰일 것입니다.간단한 방법은 원본 코드에서 $의 이름을 따로 짓는 것이다.그러나 만약에 기존의 원본 코드 라이브러리에서 얻은 원본 코드라면 버전이 업데이트될 때마다 그 함수의 이름을 바꿔야 하기 때문에 이 해결 방안은 이상적이지 않다.이 경우 더 좋은 해결 방법은 다음과 같이 설치기(install)를 추가하는 것이다.
    Function.prototype.method = function(name, fn){
        // ...
    };
    
    (function(){
        function _$(els){
            // ...
        }
        _$.method("addEvent", function(type, fn){
            // ..
        });
    
        window.installHelper = function(scope, interface){
            scope[interface] = function(){
                return new _$(arguments);
            }
        };
    })();

    사용자는 이렇게 사용할 수 있습니다.
    installHelper(window, "$");

    다음은 미리 정의된 네임스페이스 객체에 이러한 기능을 추가하는 방법을 보여 주는 더 복잡한 예입니다.
    //         ,          
    window.com = window.com || {};
    com.example = com.example || {};
    com.example.util = com.example.util || {};
    
    installHelper(com.example.util, "get");
    
    (function(){
        var get = com.example.util.get;
        get("example").addEvent("click", function(){
            get(this).addClass("hello");
        });
    })();

    소결


    JavaScript에서 객체는 참조로 전달됩니다.그래서 너는 모든 방법을 대상의 인용으로 돌려보낼 수 있다.만약 하나의 클래스의 모든 방법을this값으로 되돌려준다면, 그것은 지원하는 방법의 체인 호출 클래스가 될 것이다.

    좋은 웹페이지 즐겨찾기