Prototype.js 가이드 01

WEB2.0/ajax | 2006. 5. 10. 11:32
Posted by 시반

Prototype은 무엇인가.?

prototype.jsSam Stephenson에 의해 작성된 자바스크립트 라이브러리이며 웹2.0의 특성에 따라 작성된 코드들은 비동기적 웹페이지 구현시 많은 도움을 줄 수 있을 것입니다

 

 

ProtoType의 사용

 

prototype은 http://prototype.conio.net/에서 다운 받을 수 있으며 구현하고자 하는 페이지에서 다음과 같은 구문을 추가하면 prototype framework를 사용할 수 있다

 

<script src="/scripts/prototype.js" type="text/javascript"></script>

라이브러리를 사용하는 것은 반복적인 타이핑과 어구를 많이 줄일수 있게 됨으로서 작업 생산성 및 효율성을 높이는 데 있다

당연히 prototype.js에도 미리 정의된 많은 수의 객체와 유틸리티 함수를 가지게 되는데 어떤 것들이 있는지 살펴보도록 한다

 

유틸리티 함수들(utility functions)

 

$() 함수 사용하기

$()함수는 가장 많이 사용되는 DOM의 document.getElementById()함수에 대한 편리한 단축키라고 할 수 있다. 예를 들면 DOM함수를 통해 특정id를 가진 요소 하나를 가져온다고 하자

 

 node = document.getElementById("elementID");

 

위의 식은 $()를 사용하여 다음과 같이 바꿀수 있다 

 

 node = $("elementID"); 

 

하지만 $()함수는 DOM함수와는 달리 여러개의 id를 사용할수 있다는 장점이 있다 이 때 반환하는 값은 Array객체를 반환한다

 

 allNodes = $("firstDiv", "secondDiv");

 

 for(i = 0; i < allNodes.length; i++) {

    alert(allNodes[i].innerHTML);

 }

 

이 함수의 또 다른 장점은 이 함수를 통하여 id문자열이나 요소객체 자체를 전달할 수 있기

때문에 인자타입을 가지는 다른 함수를 생성할때 매우 유용하다

$F() 함수 사용하기

$F() 함수는  DOM의 document.getElementById()함수에 대한 또 다른 단축키라 할 수 있다.

이것은 text박스나 드랍다운 list와 같은 어떤 필드의 입력 컨트롤의 값을 반환한다. 

마찬가지로 요소 id나 요소객체 자체를 인자로 가질수 있다.

 

예를 들면 다음과 같은 Form필드가 존재한다고 하자

 <input type="text" id="textfield" name="textfield" />

 <textarea rows="5" cols="5" id="areafield" name="areafield"></textarea>

 <select id="selectfield" name="selectfield">

    <option value="1" selected>One</option>

    <option value="2">Two</option>

 </select>

 <input type="checkbox" id="checkfield" name="checkfield" value="1" checked />

각각의 필드값은 다음과 같이 가져올 수 있다

 $F("textfield");     // returns the value of the text input

 $F("areafield");   // returns the value of the textarea

 $F("selectfield"); // returns the selected value of the select

 $F("checkfield"); // returns undefined if not checked, or the value

 

$F()을 통해 쉽게 입력컨트롤의 값을 쉽게 가져올 수 있지만

라디오그룹에서는 사용하기 힘들다는 점과 $()와 같이 다수의 인자를 가질수 없다

$A() 함수 사용하기

$A() 함수는 인자들을 하나의 인자로 받아들여 Array객체로 변환한다

 

Array Class상속을 겸한 이 함수는 어떠한 enumerable list 형태도 Array객체로 변환 또는 복사 할 수 있다는 장점이 있다

예를 들면 다음과 같이 DOM의 NodeLists를 regular Arrays로 변환하기에 유용하다 

 <script>
    function showOptions() {
      var someNodeList = $('lstEmployees').getElementsByTagName('option');
      var nodes = $A(someNodeList);
      nodes.each(function(node) {
                         alert(node.nodeName + ': ' + node.innerHTML);
                       });
    }
 </script>
 
 <select id="lstEmployees" size="10" >
   <option value="5">Buchanan, Steven</option>
   <option value="8">Callahan, Laura</option>
   <option value="1">Davolio, Nancy</option>
 </select>
 
 <input type="button" value="Show the options" onclick="showOptions();">

 

 

$A() 의 또 하나의 장점은 함수생성시 인자의 수를 유연하게 받아들이게 한다는 점이다

 <script>

   function shoutOut(){

       sayHi('Hello, ', 'Homer', 'Bart', 'Marge', 'Snowball');

   }

 

   function sayHi(){

      var names = $A(arguments).slice(1);

      var phrase = arguments[0];

      for(i=0; i<names.length; i++)

          alert(phrase + names[i]);

   }

 </script>

 <input type="button" value="Say hi to everybody" onclick="shoutOut();" >

$H() 함수 사용하기

$H() 함수는 결합된 배열처럼 보이는 Hash객체로 변환한다.

 <script>

    function testHash() {

        var a = []; //let's populate the associative array

        a['first'] = 10;

        a['second'] = 20;

        a['third'] = 30;

 

        //now transform it into a hash

       var h = $H(a);

       alert(h.toQueryString());

       //displays: first=10&second=20&third=30 }

 </script>

$R() 함수 사용하기

$R() 함수는 new ObjectRange(lowerBound, upperBound, excludeBounds) 형태의 다른 표현이다. 이 클래스에 대하여는 ObjectRange 클래스 문서를 통해 확인해보시길 바라며. 다음은 each 메소드를 통해 반복(iterators)의 사용법을 보여주는 간단한 예제입니다.

더 많은 메소드는 Enumerable 클래스 문서에서 보실 수 있습니다.

 <script>

    function demoDollar_R()

    {

       var range = $R(10, 20, false);

       range.each(function(value, index)

                         { alert(value); });

     }

 </script>

 <input type="button" value="Sample Count" onclick="demoDollar_R();" >

Try.these() 함수 사용하기

Try.these()함수는 개발자가 across Browser구현시 서로 다른 javascript등을 작성할 필요가 있는 코드생성시 도움을 주는 중요한 함수입니다

이 함수는 인자처럼 많은 수의 함수를 가지고 그것들을 순차적으로 호출하도록 해준다. 이것은 함수중에 하나씩 수행하고 성공적인 함수호출의 결과를 반환할때까지 순차적으로 수행된다.

 <script>

     function test(){
       return Try.these(
        function() {
            alert("first");
            jkgjhgjhg        //intentional error
            alert("firsterror");
            return 1;
        },
        function() {
            alert("second");
            return 2;
        }
     );
    }

 </script>

 

 <input type="button" value="Try_these_test" onclick="test();" >

 
블로그 이미지

시반

시반(詩伴)이란 함께 시를 짓는 벗이란 뜻을 가지고 있습니다. 함께 나눌수 있는 그런 공간이길 바라며...

카테고리

분류 전체보기 (233)
개발 이야기 (73)
WEB2.0 (57)
DB2 (24)
MySQL (6)
오라클 (26)
기타 (44)
취미 (0)
잡담 (2)