ExtJs 소스 코드 분석 및 학습 - ExtJs 핵심 코드 (3)

Ext 는 javascript 의 일부 대상 을 확장 하 였 으 며, 주로 String, Array, Function 이 있 습 니 다. 다음은 Ext. js 에서 언급 한 방법 만 소개 하고, 기타 후속 은 다시 소개 합 니 다.
 
Ext 는 String 의 방법 format 를 확장 합 니 다. 이 방법 은 String 의 정적 방법 (클래스 방법) 입 니 다. 문자열 의 특수 쓰기 ({0}, {1}) 를 지정 한 변수 로 대체 할 수 있 습 니 다.
 
//         ,           。          ,      {0},{1}...{n}
 //      。
 //var cls = 'my-class', text = 'Some text';
 //var s = String.format('{0} '  '{1}', cls, text);
    //s      :s now contains the string: 'my-class'   'Some text'

    format : function(format){
        var args = Ext.toArray(arguments, 1);
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    }


   Ext 는 Array 를 위해 index Of 와 remove 방법 을 확장 하 였 으 며, 이 두 가지 방법 은 각각 색인 과 하위 요소 에 따라 해당 하 는 요 소 를 삭제 하 는 것 을 실현 하 였 다.
Ext.applyIf(Array.prototype, {
    /**
     * Checks whether or not the specified object exists in the array.
     * @param {Object} o The object to check for
     * @param {Number} from (Optional) The index at which to begin the search
     * @return {Number} The index of o in the array (or -1 if it is not found)
     */
    indexOf : function(o, from){
        var len = this.length;
        from = from || 0;
        from += (from < 0) ? len : 0;
        for (; from < len; ++from){
            if(this[from] === o){
                return from;
            }
        }
        return -1;
    },

    /**
     * Removes the specified object from the array.  If the object is not found nothing happens.
     * @param {Object} o The object to remove
     * @return {Array} this array
     */
    remove : function(o){
        var index = this.indexOf(o);
        if(index != -1){
            this.splice(index, 1);
        }
        return this;
    }
});


 
편집 자 는 실제 개발 에서 다음 과 같은 두 가지 방법 을 자주 사용 하고 실 용적 이다.
 
/**
  *       
  * @param {} index     
  * @param {} o     
  * @return {}
  */
 insert : function (index,o){
  if(index <= 0){
            return this.unshift(o);//      
        }
        if(index >= this.length){
            return this.push(o);//      
        }
        var sub = this.slice(index, this.length);
        this.length = index;
        this.push(o);
        for(var i = 0; i < sub.length; i++){
         this.push(sub[i]);
        }
        return this;
 },
 
 /**
  *           
  * @param {} index
  * @return {}
  */
 removeAt : function(index){
        if(index != -1){
            this.splice(index, 1);
        }
        return this;
    }

 
아래 확장 String 방법 도 유용 합 니 다.
Ext.applyIf(String,{
 
 /**
  *             -  
  * alert(humpToConnector('aaaBbbCcc','-')); //return aaa-bbb-ccc
  * @param {} str
  * @param {} conj
  * @return {}
  */
    humpToConnector : function(str, conj){
  //str = !str ? str : String(str);
  var index = str.search(/[A-Z]/);
  if (index >= 0) {
   var c = str.charAt(index);
   return String.humpToConnector(str.substring(0, index) + conj
       + c.toLowerCase() + str.substring(index + 1), conj);
  } else {
   return str;
  }
 }
});

 
Ext 기능 확장
 
createInterceptor 방법
createInterceptor : function(fcn, scope){
        var method = this;
        return !Ext.isFunction(fcn) ?
                this :
                function() {
                    var me = this,
                        args = arguments;
                    fcn.target = me;
                    fcn.method = method;
                    return (fcn.apply(scope || me || window, args) !== false) ?
                            method.apply(me || window, args) :
                            null;
                };
    },
 
이 방법 은 차단기 와 유사 한 기능 을 실현 하고 전 달 된 매개 변수 fcn 은 원 함수 전에 호출 됩 니 다.fcn 의 반환 값 이 false 라면 원 함수 가 호출 되 지 않 습 니 다.즉 함수 fcn 차단 시 fcn 이 false 로 돌아 가면 차단 되 고 true 는 실 행 됩 니 다.다음은 방법 중의 일부 문 구 를 설명 한다.
 
var method = this 는 Function. prototype 에 확장 되 기 때문에 prototype 에 걸 려 있 는 모든 함수 입 니 다. 함수 안의 this 는 모두 Function, 즉 함수 자체 입 니 다.아래 의 예 를 보시오
Function.prototype.test = function(){
	alert(this);
};
function fn(){return 'test';}
fn.test();

  결과 출력
function fn() {
    return "test";
}
즉 this 는 fn 함수 자체 입 니 다.
 
!Ext. is Function (fcn), 이 조건 은 전 달 된 매개 변수 fcn 이 function 이 아니라면 this, this 즉 함수 자신 을 직접 되 돌려 줍 니 다.혹은 이 때 는 아무런 차단 도 하지 않 고 함수 자신 을 되 돌려 주 었 다.
 
fcn 이 하나의 function 일 때 ":" 후의 가 지 를 실행 합 니 다. 이때 fcn 에 두 개의 속성 target, method 를 추가 합 니 다.target 은 me, me 는 this.
이때 의 this 는 무엇 일 까요?대부분의 경우 window 이지 만 전체 function 이 대상 속성 으로 존재 할 때 this 는 이 대상 입 니 다.누가 createInterceptor 를 호출 했 습 니까? method 는 누구 입 니까?예:
 
function oldFn(){
	alert('test');
}
function ret(){
	return false;
}
var newFn = oldFn.createInterceptor(ret);
newFn();

oldfn 은 createInterceptor 방법 을 계승 하고 호출 했 습 니 다. 매개 변 수 는 ret 입 니 다.이때 createInterceptor 내부 의 method, fcn. method 가 oldfn 입 니 다.me, fcn. target 은 window 대상 입 니 다.다음 과 같이 변경 합 니 다. me, fcn. target 은 obj 입 니 다.
 
function oldFn(){
	alert('test');
}
function ret(){
	return false;
}
var obj = {name:'jack'};
obj.method = oldFn.createInterceptor(ret);
obj.method();

  (fcn. apply (scope | me | window, args)! = = false), 전 달 된 매개 변수 fcn 이 실 행 됩 니 다. 컨 텍스트 우선 은 scope 이 고, 그 다음은 me 이 며, 마지막 은 window 입 니 다.결 과 를 되 돌려 주 는 것 은 false 가 아니 라 method 를 실행 합 니 다.method 실행 컨 텍스트 는 me 이 고 me 가 존재 하지 않 으 면 window 입 니 다.
 
지금 공식 예 를 붙이다
var sayHi = function(name){
    alert('Hi, ' + name);
}

sayHi('Fred'); // alerts "Hi, Fred"

// create a new function that validates input without
// directly modifying the original function:
var sayHiToFriend = sayHi.createInterceptor(function(name){
    return name == 'Brian';
});

sayHiToFriend('Fred');  // no alert
sayHiToFriend('Brian'); // alerts "Hi, Brian"

 
이 예 는 createInterceptor 에서 fcn. apply (scope | me | window, args) 는 직접 실행 하 는 것 과 같 습 니 다.
function(name){
    return name == 'Brian';
}
함수 만 다른 대상 에 연결 (scope | me | window) 하여 실행 합 니 다.
method 는 실제 sayHi 입 니 다.
 
createCallback 방법
 
//        ,           :arguments[0],...
    createCallback : function(/*args...*/){
        // make args available, in function below
        var args = arguments,
            method = this;
        return function() {
            return method.apply(window, args);
        };
    },
 
이 방법 은 매우 유용 하고 실현 이 간단 하 다.새 함 수 를 되 돌려 줍 니 다. 새 함수 에서 method 를 실행 하면 밖의 매개 변 수 를 전달 합 니 다.초보 자  이벤트 handler 에 전달 하 는 매개 변수 에 얽 매 여 있 습 니 다.  。createCallback 은 DOM 이벤트 handler (감청 기) 에 전달 하 는 문 제 를 해결 했다.createCallback 은 DOM 이벤트 handler 뿐만 아니 라 이 벤트 를 사용자 정의 할 수 있 습 니 다. 자신 만 의 것 을 디자인 할 수 있 습 니 다  관찰자 모드 API。즉, 모든 유형 은 자신의 사건 이 있다.  LTMaps  ,속성 을 가지 고 있 는 것 외 에 도 방법 은 많은 이벤트 가 있 습 니 다. 예 를 들 어 지도 이동 (move), 지도 크기 조정 (zoom) 등 이 있 습 니 다.Ext 의 많은 UI 구성 요소 도 이러한 모드 입 니 다. Ext.Panel 애 프 터 레이아웃, close 등 사건 이 있 습 니 다.
이 이벤트 들 에 hanlder 를 추가 하고 인삼 을 전달 하려 면 createCallback 도 사용 할 수 있 습 니 다.
 
 
createDelegate 방법
 
//        (    ),         obj。                 。
    //obj : Object (   )          。(optional) The object for which the scope is set 
    //args : Array (   )            。(       arguments)。(optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) 
    //appendArgs : Boolean/Number(   )       true, args         ,          , args          。
    //     Array.prototype.slice(start,end)   ,            ,start,end    ,         
    createDelegate : function(obj, args, appendArgs){
        var method = this;
        return function() {
            var callArgs = args || arguments;
            if (appendArgs === true){
                callArgs = Array.prototype.slice.call(arguments, 0);
                callArgs = callArgs.concat(args);
            }else if (Ext.isNumber(appendArgs)){
                callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
                var applyArgs = [appendArgs, 0].concat(args); // create method call params
                Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
            }
            return method.apply(obj || window, callArgs);
        };
    },

 
createDelegate 는 createCallback 보다 더 강력 합 니 다. 리 셋 함수 전송 문 제 를 해결 할 수 있 는 것 을 제외 하고.제어 가능: 1, 사용자 정의 매개 변수 가 기본 매개 변 수 를 덮어 쓸 지 여부 (예:  DOM 이벤트 대상  handler 첫 번 째 매개 변수) 2, 사용자 정의 매개 변수의 위치 내부 구현: 자신 (var method = this) 을 가 져 와 새로운 function 을 되 돌려 줍 니 다. 이 function 은 자신 (method. apply) 을 호출 하고 컨 텍스트 (obj | window) 와 매개 변수 (callArgs) 를 지정 합 니 다.이렇게 간단 하고 세부 적 인 점 은 매개 변수 에 대한 통제 에 있다.1. obj 와 args 만 전송 할 때 리 셋 함수 기본 매개 변수 (DOM 이벤트 대상) 를 덮어 씁 니 다.
<a href="#" id="aa">SINA</a>
<script type="text/javascript">
	var aa = document.getElementById('aa');
	function sayName(name){
		alert('hello, ' + name);
	}
	var sayName2 = sayName.createDelegate(aa,['jack']);
	aa.onclick = sayName2;
</script>

 2. 세 개의 매개 변 수 를 모두 전달 합 니 다. appendArgs 가 true 일 때 기본 매개 변수 (DOM 이벤트 대상) 의 위치 가 변 하지 않 습 니 다 (첫 번 째). 사용자 정의 매개 변수 args 는 마지막 에 있 습 니 다.
<a href="#" id="aa">SINA</a>
<script type="text/javascript">
	var aa = document.getElementById('aa');
	function sayName(){		
		alert('      :' + arguments.length);
		alert('hello, ' + arguments[0]);
		alert('hi, ' + arguments[1]);
	}
	var sayName2 = sayName.createDelegate(aa,['jack'],true);
	aa.onclick = sayName2;
</script>

 3. 세 개의 매개 변 수 를 모두 전달 하고 appendArgs 가 숫자 일 때 사용자 정의 매개 변수의 위 치 를 지정 합 니 다.
<a href="#" id="aa">SINA</a>
<script type="text/javascript">
	var aa = document.getElementById('aa');
	function sayName(name){		
		alert('      :' + arguments.length);
		alert('hello, ' + arguments[0]);
		alert('hi, '+ arguments[1]);
		alert('hi, '+ arguments[2]);
	}
	var sayName2 = sayName.createDelegate(aa,['jack','lily'],0);
	aa.onclick = sayName2;
</script>

 
defer 방법
 
/**
     *        
     * @param {} millis     ,      (   0     )
     * @param {} obj (   ) fcn    (        window)
     * @param {} args (   )           (       arguments)
     * @param {} appendArgs (   )      true, args         ,          , args          
     * @return {Number}
     */
    defer : function(millis, obj, args, appendArgs){
        var fn = this.createDelegate(obj, args, appendArgs);
        if(millis > 0){
            return setTimeout(fn, millis);
        }
        fn();
        return 0;
    }
 
 
 

좋은 웹페이지 즐겨찾기