// variable to store whether document has been opened already or not
var bAlreadyOpened;

function docOpened()
{

	if(bAlreadyOpened != "true")
	{
		// document has just been opened
		var d = new Date();
		var sDate = util.printd("mm/dd/yyyy", d);

                // set date now
                app.alert("About to insert date into field now");
		this.getField("todaysDate").value = sDate;

		// now set bAlreadyOpened to true so it doesn’t
		// run again
bAlreadyOpened = "true";
	}
	else
	{
		// document has already been opened
	}
}

// call the docOpened() function
docOpened();

ppjslc_commonex_3.pdf
0.08MB

출처 : Example Acrobat JavaScripts – Planet PDF

/********************************
RSCivilTools by Andrew Binning
Version 01, 2-15-2012
********************************/
//Some code by:
// InDesign Fixups by Dave Merchant  - Creative Commons Share-alike license
// version 02, November 2010
// http://www.uvsar.com/go/indesignfixups

//create new submenu for the Acrobat 8/9 or X menus
//Determine version, assign menu location
var menuParent = (app.viewerVersion<10)? "DocumentProcessing":"Edit";
//Add the menu
app.addSubMenu({ cName:"RSCivilTools", cUser:"RSCivil Tools", cParent:menuParent, nPos:((app.viewerVersion<10)? 0:7) });
//Create a nested layer (tailored code for my specific Document.
app.addMenuItem({ cName:"RSCcreateNest", cUser:"Create Nest", cParent:"RSCivilTools", 
          cExec:"createNest();",
          cEnable:"event.rc = (event.target != null);", nPos:0 });
//Promote sub layers - Unravel the nests
app.addMenuItem({ cName:"RSCpromote", cUser:"Undo Nest", cParent:"RSCivilTools",
          cExec:"promoteOCG_handler(event.target);",
          cEnable:"event.rc = (event.target != null);", nPos:1 });
//Unlist Guides and Grids layer (from Adobe IN-Design)
app.addMenuItem({ cName:"RSCremGAG", cUser:"Unlist 'Guides and Grids'", cParent:"RSCivilTools",
          cExec:"removeGAG(event.target);",
          cEnable:"event.rc = (event.target != null);", nPos:2 });
//Set up layers ( this is tailored code for my specific Document)
app.addMenuItem({ cName:"RSCsetStates", cUser:"Set Layers", cParent:"RSCivilTools",
          cExec:"setStates();",
          cEnable:"event.rc = (event.target != null);", nPos:3 });
//Toggle this list of layers on and off (tailored code for my specific Document.
app.addMenuItem({ cName:"RSCtoggleCityLimits", cUser:"Toggle City Limits", cParent:"RSCivilTools",
          cExec:"toggleCityLimits();",
          cEnable:"event.rc = (event.target != null);", nPos:4 });
//Link to the company website         
app.addMenuItem({ cName:"RSCsite", cUser:"Website", cParent:"RSCivilTools", 
          cExec:"app.launchURL('http://rscivil.com');", nPos:5 });

//Add a button for this function - Add from Quick Tools 3rd party addons
app.addToolButton({
        cName: "RSCcreateNestButton",
        cExec: "createNest();",
        cTooltext: "Create Nest",
        cEnable: true,
        nPos: 0,
        cLabel: "Create Nest"
        })
//Add a button for this function - Add from Quick Tools 3rd party addons
app.addToolButton({
        cName: "promoteLayers",
        cExec: "promoteOCG_handler(event.target);",
        cTooltext: "Undo Nest",
        cEnable: true,
        nPos: 1,
        cLabel: "Undo Nest"

        })

//Creates a nested layer from a predetermined list
function createNest(){
    var layers = this.getOCGs();
    var newOrder = new Array();
    var cityLimits = new Array();
    var comps = new Array();

    /*******************************************************
    This is where I need help.
    By not setting the first element to a String it does not name the group. Instead it seems to attach it as a child to the previous element in the array.
    This is fine, except that when you turn off said parent it does not turn off the sub layers/OCGs.
    If I could figure out how to create an object and set it up as an element before my inserted array it might help.
    *******************************************************/
    //Commented for testing - Set first element of the array to a descriptive string (this will be the name of the nested group) 
    //cityLimits[0] = "City Limits";
    //Set first element of the array to a descriptive string (this will be the name of the nested group)
    comps[0] = "Comps";

    //Separate all layers/OCGs containing "CityLimits|" or "COMP" from the original list of layers/OCGs
    for (var i=0,j=0,k=0,l=1; i<layers.length; i++){
        if(layers[i].name.substr(0,11)==="CityLimits|"){
            cityLimits[j] = layers[i];  //separate CityLimits OCG
            j++;
        }
        else if(layers[i].name.substr(0,4)==="COMP"){
            comps[l] = layers[i];   //separate COMP OCG
            l++;
        }
        else{
            newOrder[k] = layers[i];    //cram everything else into a new array
            k++;
        }
    }
    //Insert the cityLimits array into the newOrder array at position 5, do not remove any elements (the element before this arbitrarily becomes the parent, but does not work correctly)
    newOrder.splice(5,0,cityLimits);
    //Append the comps array to the end of the newOrder array
    newOrder[newOrder.length] = comps;
    //set the newOrder array as the OCGOrder.
    this.setOCGOrder(newOrder);
}
//Code by Dave Merchant
//Handler for promoting OCGs out of nested layers
function promoteOCG_handler(oDoc) {

  var ocgOrder = oDoc.getOCGOrder();
  var hasNest = false;

  if (ocgOrder==null) {
    app.alert( "No layers in current file", 0, 0, "Cannot proceed");
  } else {
    for (var i=0; i<ocgOrder.length; i++) {
       if ((typeof(ocgOrder[i]) == "object") && (ocgOrder[i].length > 0)) hasNest = true;
    }
    if (hasNest)  {
      promoteOCGs(oDoc,ocgOrder);
    } else app.alert( "No nested layers in current file", 0, 0, "Cannot proceed");
  }
}
//Code by Dave Merchant
//Promote/unravel layers/OCG out of nests
function promoteOCGs(oDoc,ocgOrder) {

  // Removes the top-level OCG nest structure from a PDF, promoting all sub-OCGs to the top level.
  // Used to remove the nesting created when a PDF is exported from InDesign with "Create Acrobat Layers" checked.


  var oChk = { cMsg:"Unlist the 'Guides and Grids' layer?", bInitialValue:true, bAfterValue:false};

  //var cMesg = "This action will ungroup all nested layers. IT CANNOT BE UNDONE.\n\nDo you want to continue?";
  //var nRtn = app.alert({ cMsg:cMesg, nIcon:2, nType:2, cTitle:"Promote nested layers", oCheckbox:oChk});
  //if (nRtn == 4) {

    var newOrder = new Array();

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

     var oType = typeof(ocgOrder[i]);
     var oLeng = ocgOrder[i].length
     if ((oType == "object") && (oLeng > 0)) {      // it's a nest, do the promotions

        for (var j=0; j<oLeng; j++) {
           if ((typeof(ocgOrder[i][j]) == "object") && 
              (!oChk.bAfterValue || (ocgOrder[i][j].name != "Guides and Grids"))) newOrder.push(ocgOrder[i][j]);
        }

     } else if (!oChk.bAfterValue || (ocgOrder[i].name != "Guides and Grids")) newOrder.push(ocgOrder[i]);
    }
    oDoc.setOCGOrder( newOrder );
  //}
}


//Code by Dave Merchant
// Removes the listing for (sub)OCG named "Guides and Grids".
// Does NOT delete the layer, simply hides it from the sidebar display.
function removeGAG(oDoc) {
  var cMesg = "This action will unlist the 'Guides and Grids' layer from the sidebar but will NOT delete the ";
  cMesg += "layer itself. IT CANNOT BE UNDONE.\n\nDo you want to continue?";
  var nRtn = app.alert(cMesg, 2, 2, "Unlist 'Guides and Grids'");
  if (nRtn == 4) {

    var ocgOrder = oDoc.getOCGOrder();
    var newOrder = new Array();

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

     var oType = typeof(ocgOrder[i]);
     var oLeng = ocgOrder[i].length
     if ((oType == "object") && (oLeng > 0)) {      // it's a nest

        var subObj = new Array();
        for (var j=0; j<oLeng; j++) {
           if ((typeof(ocgOrder[i][j]) == "string") || (ocgOrder[i][j].name != "Guides and Grids")) subObj.push(ocgOrder[i][j]);
        }
        newOrder.push(subObj);

     } else if (ocgOrder[i].name != "Guides and Grids") newOrder.push(ocgOrder[i]);
    }
    oDoc.setOCGOrder( newOrder );
  }
}

//Just a list of layers I want to toggle on or off (document specific)
function togList(name){
    if(name.substr(0,11)==="CityLimits|")
        return true;
    return false;
}
//Just a list of layers I want to set an initial state to off (document specific)
function offList(name){
    var lOff =  new Array();
    lOff[0] = "ADT";
    lOff[1] = "CityLimits|1900";
    lOff[2] = "CityLimits|1910";
    lOff[3] = "CityLimits|1920";
    lOff[4] = "CityLimits|1930";
    lOff[5] = "CityLimits|1940";
    lOff[6] = "CityLimits|1950";
    lOff[7] = "CityLimits|1960";
    lOff[8] = "CityLimits|1970";
    lOff[9] = "CityLimits|1975";
    lOff[10] = "CityLimits|1980";
    lOff[11] = "CityLimits|1985";
    lOff[12] = "CityLimits|1990";
    lOff[13] = "CityLimits|1995";
    lOff[14] = "CityLimits|2000";
    lOff[15] = "CityLimits|2005";
    lOff[16] = "CityLimits|2006";
    lOff[17] = "CityLimits|2007";
    lOff[18] = "CityLimits|2008";
    lOff[19] = "CityLimits|2009";
    lOff[20] = "CityLimits|2010";
    lOff[21] = "CityLimits|2011";
    lOff[29] = "Distance Circles 1";
    lOff[30] = "Distance Circles 2";
    lOff[31] = "landuse|Agriculture";
    lOff[32] = "landuse|Industrial";
    lOff[33] = "Landmark Labels Locations";
    lOff[34] = "landmarks|Locations";

    for (var i=0; i<lOff.length; i++){
        if(lOff[i] === name)
            return true;
    }
    return false;
}

//Checks all layers against a list and toggles them off or on (document specific)
function toggleCityLimits(){
   var layers = this.getOCGs();
    for (var i=0; i<layers.length; i++){
        var tog = true;
        if(togList(layers[i].name)){
            if(layers[i].state)
                tog = false;
            layers[i].state = tog; //toggle layer
        }
    }
}

//Checks all layers against a list and sets the initial state and current state to off (state=visibility) (document specific)
function setStates(){
   var layers = this.getOCGs();
    for (var i=0; i<layers.length; i++){
        var tog = true;
        if(offList(layers[i].name))
            tog = false;
        layers[i].state = tog;      //turn off layer
        layers[i].initState = tog;  //set initial visibilty to off
    }
}

출처 : http://www.uvsar.com/go/indesignfixups

syncAnnotScan();

var strFDF = exportAsFDFStr({bAllFields: 'true', bFlags: 'true', bAnnotations: 'true'});
//exportAsXFDFStr(true, true, null, true, 1);";

var strXFDF = exportAsXFDFStr(true, true, true, true, 1);
//exportAsXFDFStr(true, true, null, true, 1);

exportAsFDF({ bAnnotations: 'true', cPath: '/d/export.fdf'});


importAnFDF("/d/import.fdf");
importAnXFDF("/d/import.xfdf");
// Add navigation buttons to the page
// This script puts 3 buttons on top of every page (except the first one that has one button)
// First button "<" : takes to the previous page
// Second button: "1" : takes to the first page of the document
// Third button: ">" : takes to the next page in the document (does not exists on the last page)

var inch = 72;

try 
{

    nLastPage = this.numPages - 1;

    for (var p = 0; p < this.numPages; p++)
    {
        var x = 0.5;
 
        if (p > 0)
        {
            AddButton(p,x,0.5,0.25,0.25,"PrevPage","<","Previous Page","this.pageNum--;"); // left arrow, previous page
            x += 0.3;
        }
    
        if (p != 0)
        {
            AddButton(p,x,0.5,0.25,0.25,"StartPage","1","Go To First Page","this.pageNum=0;"); // "1", takes to the first page
            x += 0.3;
        }
    
        if (p < nLastPage)
        {
            AddButton(p,x,0.5,0.25,0.25,"NextPage",">","Next Page","this.pageNum++;"); // right arrow, next page
            x += 0.3;
        }

        AddButton(p,x,0.5,0.25,0.25,"Back","<<","Go Back","app.execMenuItem(\"GoBack\");"); // right arrow, next page
        x += 0.3;
        
    }

}


catch (e)
{
app.alert(e);
}

// AddButton function creates a button with given parameters and action

function AddButton(nPageNum, x, y, width, height, strText, strCaption, strToolTip, strAction)
{
    var aRect = this.getPageBox( { nPage: nPageNum} );
    aRect[0] += x * inch;
    aRect[1] -= y * inch;
    aRect[2] = aRect[0] + width * inch;
    aRect[3] = aRect[1] - height * inch;

    var f = this.addField(strText,"button", nPageNum, aRect);
    f.setAction("MouseUp",strAction);
    f.userName = strToolTip;
    f.delay = true;
    f.borderStyle = border.s;
    f.highlight = "push";
    f.textSize = 0; // autosized
    f.textColor = color.blue;
    f.strokeColor = color.blue;
    f.fillColor = color.white;
    // you can specify a different font here, otherwise it uses a default one
    //f.textFont = font.ZapfD;
    f.buttonSetCaption(strCaption); 
    f.delay = false;
}

 

출처 : https://www.evermap.com/javascript.asp

var annots = this.getAnnots();
console.clear();
for (var i = 0; i < annots.length; i++) 
{
	//console.println(annots[i].toString());
	//if (annots[i].type == "PolyLine") 
	{  
		var a = annots[i].getProps();
		for(var o in a)
		{
			console.println( "annots." + o + "=" + a[o]);
		}
		console.println( "==========================")
		++counter;   
	}
}

app.alert("Total comments count: " + annots.length + " / : " + counter);
var annotText = this.addAnnot({
	page: 0,
	type: "FreeText",
	textFont: "Arial", // or, textFont: "Viva-Regular",
	textSize: 7,
	rect: [57.806640625,730.9102172851562,75.806640625,744.916015625],
	width: 0,
	alignment: 1,
	contents: "D",
	lineEnding : "None",
	refType : "R",
	seqNum : 1
});

var annotPoly = this.addAnnot({
	page: 0,
	type: "PolyLine",
	rect: [55.78631591796875,730.4441528320312,73.8094482421875,747.8836059570312], // height for three lines
	reftype : "R",
	rotation: -270,
	vertices: [[73.25311279296875,738.8373413085938],[56.49212646484375,747.6712036132812],[56.367919921875,730.8611450195312],[73.25311279296875,738.8373413085938]],
	with: 0.75,
	seqNum : 2
});
var annot = this.addAnnot({
	page: 0,
	type: "Text",
	point: [72,500],
	popupRect: [72, 500,6*72,500-2*72],
	popupOpen: true,
	noteIcon: "Help"
});

var spans = new Array();
spans[0] = new Object();
spans[0].text = "Attention:\r";
spans[0].textColor = color.blue;
spans[0].textSize = 18;

spans[1] = new Object();
spans[1].text = "Adobe Acrobat 6.0\r";
spans[1].textColor = color.red;
spans[1].textSize = 20;
spans[1].alignment = "center";

spans[2] = new Object();
spans[2].text = "will soon be here!";
spans[2].textColor = color.green;
spans[2].fontStyle = "italic";
spans[2].underline = true;
spans[2].alignment = "right";

// Now give the rich field a rich value
annot.richContents = spans;

출처 : https://www.gdpicture.com/forum/viewtopic.php?t=6250#p19870 

 

Adding multiline rich text - GdPicture Imaging Forums

Post by radshat » Wed Dec 13, 2017 12:31 am I need to be able to create multiline rich text annotation. The Acrobat JavaScript API reference allows the following. What is the equivalent in GdPicture? I don't mind doing this as a custom action on the serve

www.gdpicture.com

 


Windows 플랫폼에서 alert 객체가 지원되지 않아서 Ionic Popup객체로 대체...


var alert = window.alert;


angular.module('myApp', ['ionic'])

.controller('myCtrl', function ($scope, $state, $timeout,$ionicPopup) {
    alert = function (messageText, titleText) {
        if (!titleText || titleText == "undefined") {
            titleText = "";
        }
        var alertPopup = $ionicPopup.alert({
            title: titleText,
            template: messageText
        });
        alertPopup.then(function (res) { });
    };

});



출처 : 자작(userpark.net)


출처 : https://github.com/driftyco/ionic/issues/2885



window.addEventListener('click', function(event) {
  if (Object.prototype.toString.call(event) == '[object PointerEvent]') {
    event.stopPropagation();
  }
}
, true);


또는


ionic.Platform.isIE = function () {
    return ionic.Platform.ua.toLowerCase().indexOf('trident') > -1;
}

if (ionic.Platform.isIE()) {
    angular.module('ionic')
      .factory('$ionicNgClick', ['$parse', '$timeout', function ($parse, $timeout) {
          return function (scope, element, clickExpr) {
              var clickHandler = angular.isFunction(clickExpr) ? clickExpr : $parse(clickExpr);

              element.on('click', function (event) {
                  scope.$apply(function () {
                      if (scope.clicktimer) return; // Second call
                      clickHandler(scope, { $event: (event) });
                      scope.clicktimer = $timeout(function () { delete scope.clicktimer; }, 1, false);
                  });
              });

              // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
              // something else nearby.
              element.onclick = function (event) { };
          };
      }]);
}


'Language > Mobile' 카테고리의 다른 글

[Hybrid/Ionic]Windows Platform에서 alert 객체 대체  (1) 2016.11.04

 

상기 Libary를 이용하면 Json을 이용한 컨트롤이 Javascript에서 손쉽게 이루어 질 수 있을 것으로 판단한다.

  1. XML 파일 또는 포멧의 자료를 “XML to JSON – a converter”를 이용하여 JSON으로 변경
  2. “Sesseion variables without cookies”를 이용하여 해당 페이지에 저장(새로고침을 하여도 해당 창이 닫히기 전까지는 유지되는 기능 활용)
  3. “JSON Query Engine”을 이용하여 CRUD(Create, Read, Update, Delete) 작업 수행 및 반영

prototype.js를 위한 개발자 노트

1.5.0버전을 다룸

Sergio Pereira에 의해 작성됨
이동국에 의해 번역됨
최근 업데이트: 2007년 3월 4일

Prototype은 무엇인가.?

prototype.jsSam Stephenson에 의해 작성된 자바스크립트 라이브러리이다. 이 놀랍도록 멋진 생각과 표준에 의해 잘 작성된 코드의 일부는 웹2.0의 특성을 나타내는 풍부하고 상호작용하는 웹페이지와 많은 연관을 가진다.

만약 당신이 최근 이 라이브러리를 사용하기 시작했다면, 당신은 아마도 이 문서가 가장 좋은 지시사항중에 하나는 아니라는것을 알아차렸을것이다. 나 이전에 다른 많은 개발자들처럼, 나는 소스코드와 이것을 사용한 경험에서 prototype.js에 대한 지식을 가지게 되었다. 나는 모든 이가 배우고 공유하는 동안 좀더 많은 정보를 얻게 되는게 가장 좋은 것이라고 생각한다.

나는 objects, classes, functions, 그리고 이 라이브러리에 의해 제공되는 확장을 위한 비공식적인 참조문서 또한 제공한다.

당신이 예제와 참조문서를 읽었을때, Ruby프로그래밍 언어에 친숙한 개발자는 Ruby의 내장 클래스와 이 라이브러리에 의해 구현된 많은 확장 사이의 의도적인 유사성을 알아차리게 될것이다.

 

관련글

고급 자바스크립트 가이드

 

유틸리티 함수들

라이브러리는 미리 정의된 많은 수의 객체와 유틸리티 함수를 가진다. 이 알기쉬운 함수들의 목적은 반복적인 타이핑과 어구를 많이 줄이는데 있다.

 

$() 함수 사용하기

$()함수는 가장 많이 사용되는 DOM의 document.getElementById()함수에 대한 편리한 단축키이다. DOM함수처럼, 이것은 인자로 던져진 id를 가진 요소를 하나 반환한다.

DOM함수와는 달리 이 함수는 더 많은 작업을 수행한다. 반환된 element객체는 몇가지 추가적인 작업을 하게 될것이다. element를 숨기거나 보여주고 크기를 알아내며 element에 대해 스크롤을 하는 것과 같은 추가적인 많은 작업을 간단하게 만든다. Element 객체를 위한 참조문서에서 반환된 element객체에 추가된 메소드 목록을 얻을수 있다.

<html>
<head>
<title> Test Page </title>
<script src="prototype.js"></script>

<script>
	function test(){
		var d = $('myDiv');
		alert(d.innerHTML);
		d.hide();
		d.show();
		d.addClassName('active');
	}
</script>
</head>

<body>
	<div id="myDiv">
		<p>This is a paragraph</p>
	</div>
	<div id="myOtherDiv">
		<p>This is another paragraph</p>
	</div>

	<input type="button" value="Test $()" onclick="test();"/><br/> 

</body>
</html>

이 함수의 좋은 점은 이것은 인자형태를 가질수 있는 다른 함수를 생성할때 매우 유용하도록 만들어주는 id문자열이나 요소객체 자체를 던질수 있다는 것이다.

 

$$() 함수 사용하기

$$() 함수는 내용물에서 CSS를 일관되게 분리할때 많이 도와줄것이다. 하나 이상의 CSS필터링 표현식을 파싱한다면, CSS 룰을 정의하기 위해 사용되는 것과 유사하고 이러한 필터에 일치하는 요소를 반환한다.

이 함수는 터무니 없을 정도로 사용하기가 쉽다. 체크해보라.

<script>
function test$$(){
	/*
	  in case CSS is not your forte, the expression below says
	  'find all the INPUT elements that are inside 
	  elements with class=field that are inside a DIV
	  with id equal to loginForm.'
	*/
	var f = $$('div#loginForm .field input');
	var s = '';
	for(var i=0; i<f.length; i++){
		s += f[i].value + '/';
	}
	alert(s); // shows: "joedoe1/secret/"
	
	//now passing more than one expression
	f = $$('div#loginForm .field input', 'div#loginForm .fieldName');
	s = '';
	for(var i=0; i<f.length; i++){
		s += ( f[i].value ? f[i].value : f[i].innerHTML ) + '/';
	}
	alert(s); //shows: "joedoe1/secret/User name:/Password:/"
}


</script>

<div id='loginForm'>
	<div class='field'>
		<span class='fieldName'>User name:</span>
		<input type='text' id='txtName' value='joedoe1'/>
	</div>
	<div class='field'>
		<span class='fieldName'>Password:</span>
		<input type='password' id='txtPass' value='secret' />
	</div>
	<input type='submit' value='login' />
</div> 
<input type=button value='test $$()' onclick='test$$();' />
			

성능에 대한 빠른 노트. prototype.js에서 $$() 함수의 현재 구현체는 특별히 효과적으로 여겨지지 않는다. 이 함수를 자주 사용하여 복잡한 HTML문서를 처리하고자 계힉중이라면, 가능한 $$()함수 자체를 대체하는 다른 구현체를 고려하고자 할것이다.

 

$F() 함수 사용하기

$F() 함수는 다른 단축키이다. 이것은 텍스트 박스나 드랍다운 리스트와 같은 어떤 필드의 입력 컨트롤의 값을 반환한다. 이 함수는 요소 id나 요소객체 자체를 인자로 가질수 있다.

<script>
	function test3()
	{
		alert(  $F('userName')  );
	}
</script>

<input type="text" id="userName" value="Joe Doe"><br/> 
<input type="button" value="Test3" onclick="test3();"><br/> 
			

 

$A() 함수 사용하기

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

Array 클래스를 위한 확장과 조합된 이 함수는 열거가능한 리스트를 Array 객체로 변환하거나 복사하는 것을 더욱 쉽게 만든다. 예를 들면, 작성한 함수는 인자의 수를 유연하게 받아들인다. 여기서 추천되는 사용법은 DOM NodeLists를 좀더 효과적으로 처리할수 있도록 일반적인 배열로 변환하기 위해 사용하는 것이다. 아래의 예제를 보라.

<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();" > 
			

 

$H() 함수 사용하기

$H() 함수는 객체를 결합된 배열을 열거하는 Hash객체로 변환한다.

<script>
	function testHash()
	{
		//let's create the object
		var a = {
			first: 10,
			second: 20,
			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() 함수는 인자처럼 많은 수의 함수를 가지고 그것들을 순서대로 차례차례 호출하도록 해준다. 이것은 함수중에 하나씩 수행하고 성공적인 함수호출의 결과를 반환할때까지 순차적으로 수행된다.

아래의 예제에서 xmlNode.text 함수는 몇몇 브라우저에서 작동하고 xmlNode.textContent는 다른 브라우저에서 작동한다. Try.these()함수를 사용하면 당신은 작동하는 것 중 하나를 반환할수 있다.

<script>
function getXmlNodeValue(xmlNode){
	return Try.these(
		function() {return xmlNode.text;},
		function() {return xmlNode.textContent;}
		);
}
</script>
			

 

String을 향상시키기

String은 강력한 객체이다. Prototype.js는 그 강력함을 가지고 있으며 다른 방법으로 그 강력함을 향상시킨다.

문자열 대체

문자열 대체를 사용할때 자바스크립트는 이미 String.Replace와 같은 메소드를 제공하고 있다. 정규표현식으로 작동하지만 prototype.js에서 소개한 대체 함수만큼 유연하지는 않다.

새로운 String.gsub 메소드를 사용해보라. 이 메소드를 사용하면 고정 문자열이나 정규 표현식 패턴을 찾고 변경할수 있을 뿐 아니라 교체를 넘어서는 더 많은 제어를 하게 된다. 예를 들어 찾은 요소를 변형하고자 하는 방법을 메소드에 지시하도록 문자열 템플릿을 사용할수 있다.

아래의 예제는 't'를 포함하는 단어를 찾고 그 위치에 'tizzle' 로 변경하는 것이다. 이 예제의 경우 명확하게 설명되지는 않는다. 우리가 선택한 정규 표현식인 괄호안의 \w+은 그룹 선언을 가져온다. 대체 템플릿 문자열로 #{1}를 사용하여 이 그룹에 의해 해당되는 값을 가져올수 있다.

예제에서 우리는 't'앞의 문자들을 가져와서 'tizzle'를 뒤에 붙인다. 정규 표현식으로 더 많은 찾을 수 있다면, #{2}, #{3} 등등을 사용하여 값을 가져올것이다.

<script>
function talkLikeYouKnowSomething(){
	var s = 'prototype string extensions can help you';
	var snoopdogfy = /\b(\w+)t\w+\b/;
	var snooptalk = s.gsub(snoopdogfy, '#{1}tizzle' );
	alert(snooptalk); // shows: "prototizzle stizzle extizzle can help you"				
}
</script>
			

여기서 멈추지 말자. 우리가 만든 대체기능은 패턴에 일치하면 대체하는데 제한되기 때문에 그다지 강력하다고 보기 힘들다. 그렇다면 원하는 대체 값을 만들기 위해 사용자 정의 로직에 일치하는 작업을 할수 있을까.? gsub에 두번째 인자로 함수를 넘길수 있다면 그렇게 할수 있을것이다. 여기서 인자로 넘기는 함수는 일치하는 텍스트를 가진 배열(인덱스값이 0)을 받고 어떤 그룹값(인덱스값이 1에서 N)을 가져올것이다.

<script>
function scamCustomers(){
	var prices = 'book1 $12.5, magazine $5.50, pencil $1.20';
	var priceFinder = /\$([0-9\.]+)/;
	var r = prices.gsub(priceFinder, jackUp);
	alert(r);//shows: "book1 $13.75, magazine $6.05, pencil $1.32"
}
	
function jackUp(matches){
	//increases the prices by 10%
	var price = parseFloat(matches[1]);
   	return '$' + Math.round(110 * price)/100;
}
</script>
			

문자열 템플릿

애플리케이션에 자바스크립트 코드의 양이 증가하는 만큼, increasingly you'll find yourself with collections of objects of the same type and that you need to list or present in a formatted way.

애플리케이션에서 객체 리스트를 통해 루프를 처리하고 객체 프라퍼티와 몇가지 고정된 형태의 요소에 기초하여 문자열을 만드는 코드를 찾는것이 드물게 발생하지는 않는다. Prototype.js는 이러한 타입의 시나리오를 다루는데 도움을 주는 Template class를 가진다.

아래의 예제는 다중 HTML라인에서 장바구니에 있는 항목 리스트를 형상화하는 방법을 보여준다.

<script>
function printCart(){
	//creating a sample cart
	var cart = new Object();
	cart.items = [ ];
	//putting some sample items in the cart
	cart.items.push({product: 'Book 123', price: 24.50, quantity: 1});
	cart.items.push({product: 'Set of Pens', price: 5.44, quantity: 3});
	cart.items.push({product: 'Gift Card', price: 10.00, quantity: 4});
	
	//here we create our template for formatting each item
	var itemFormat = new Template(
			'You are ordering #{quantity} units ' + 
			'of #{product} at $#{price} each'
			);
	var formatted = '';
	
	for(var i=0; i<cart.items.length; i++){
		var cartItem = cart.items[i];
		formatted += itemFormat.evaluate(cartItem) + '<br/>\n';
	}
	
	alert(formatted);
	/* SHOWS:
	You are ordering 1 units of Book 123 at $24.5 each<br/>
	You are ordering 3 units of Set of Pens at $5.44 each<br/>
	You are ordering 4 units of Gift Card at $10 each<br/>
	*/
}
</script>
			

새로운 메소드 목록에 대한 좀더 완전한 정보를 보기 위해서는 문자열 확장 참조를 보라.

 

Ajax 객체

위에서 언급된 유틸리티 함수들은 좋다. 하지만 다시 보자. 그것들은 대부분 고급(advanced) 형태는 아니다. 당신은 스스로 이것들을 만들수 있고 당신 자신만의 스크립트에 유사한 함수를 이미 가지고 있을수도 있다. 하지만 이러한 함수들은 단지 일부분에 해당되는 팁일뿐이다.

나는 prototype.js에 대한 당신의 관심이 대부분의 AJAX기능을 다룰수 있다는 것이라고 확신한다. 그래서 당신이 AJAX로직을 수행할 필요가 있을때 좀더 쉽게 사용하도록 도와주는 라이브러리를 사용하는 방법을 살펴보자.

AJAX객체는 AJAX함수를 작성할 때 포함되는 트릭성격의 코드를 포장하고 단순화하기 위한 라이브러리에 의해 생성된 미리-정의된 객체이다. 이 객체는 캡슐화된 AJAX로직을 제공하는 많은 수의 클래스를 포함한다. 그 클래스중에 몇개를 살펴보자.


Ajax.Request 클래스 사용하기

만약 당신이 어떠한 헬퍼(helper) 라이브러리도 사용하지 않는다면, 당신은 XMLHttpRequest객체를 생성하기 위한 많은 코드를 작성할 것이고 단계를 비동기적으로 수행할것이다. 그리고나서 응답을 뽑아내고 이것을 처리한다. 그리고나서는 한가지 이상의 브라우저를 지원하지 않는다면 스스로 행운이라고 생각할 것이다.

AJAX기능을 지원하기 위해, 라이브러리는 Ajax.Request클래스를 정의한다.

당신이 다음처럼 XML응답을 반환하는 http://yourserver/app/get_sales?empID=1234&year=1998 url을 통해 서버와 통신할수 있는 애플리케이션을 가지고 있다고 해보자.

<?xml version="1.0" encoding="utf-8" ?> 
<ajax-response>
	<response type="object" id="productDetails">
		<monthly-sales>
			<employee-sales>
				<employee-id>1234</employee-id> 
				<year-month>1998-01</year-month> 
				<sales>$8,115.36</sales> 
			</employee-sales>
			<employee-sales>
				<employee-id>1234</employee-id> 
				<year-month>1998-02</year-month> 
				<sales>$11,147.51</sales> 
			</employee-sales>
		</monthly-sales>
	</response>
</ajax-response>			
			

XML을 가져오기 위해 서버와 통신하는 것은 Ajax.Request객체를 사용하면 매우 간단하다. 아래의 샘플은 이것을 수행하는 방법을 보여준다.

<script>
	function searchSales()
	{
		var empID = $F('lstEmployees');
		var y = $F('lstYears');
		var url = 'http://yourserver/app/get_sales';
		var pars = 'empID=' + empID + '&year=' + y;
		
		var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onComplete: showResponse
			});
		
	}

	function showResponse(originalRequest)
	{
		//put returned XML in the textarea
		$('result').value = originalRequest.responseText;
	}
</script>

<select id="lstEmployees" size="10" onchange="searchSales()">
	<option value="5">Buchanan, Steven</option>
	<option value="8">Callahan, Laura</option>
	<option value="1">Davolio, Nancy</option>
</select>
<select id="lstYears" size="3" onchange="searchSales()">
	<option selected="selected" value="1996">1996</option>
	<option value="1997">1997</option>
	<option value="1998">1998</option>
</select>
<br/><textarea id="result" cols=60 rows=10 ></textarea>
			

Ajax.Request객체 생성자의 두번째 파라미터를 알아보겠는가.? {method: 'get', parameters: pars, onComplete: showResponse} 파라미터는 문자적 표기법으로 익명 객체를 나타낸다. 이것이 의미하는 것은 'get' 문자열을 포함하는 명명된 메소드(method)의 프라퍼티, HTTP요청 문자열을 포함하는 명명된 파라미터(parameter)라는 프라퍼티, 그리고 함수 showResponse를 포함하는 onComplete 프라퍼티/메소드를 가지는 객체를 전달한다는 것이다.

당신이 AJAX를 비동기적으로(asynchronous) 서버에 호출할지를 결정하고 truefalse값으로 셋팅할수 있는 asynchronous(디폴트 값은 true이다.)와 같은 이 객체내 정의하고 활성화시킬수 있는 다른 프라퍼티가 몇개 있다.

이 파라미터는 AJAX호출을 위한 옵션을 정의한다. 샘플에서, 우리는 HTTP GET명령을 통해 첫번째 인자에서 url을 호출한다. 변수 pars내 포함된 조회문자열(querystring)을 전달하고 Ajax.Request객체는 응답을 받아들이는 작업을 마칠때 showResponse함수를 호출할 것이다.

당신이 아는것처럼, XMLHttpRequest는 HTTP호출을 하는 동안 진행과정을 보고한다. 이 진행과정은 4가지의 단계(Loading, Loaded, Interactive, 또는 Complete)를 알릴수 있다. 당신은 이러한 단계중에서 Ajax.Request객체 호출을 사용자정의 함수로 만들수 있다. Complete는 가장 공통적인 단계이다. 함수를 객체에게 알리기 위해, 우리 예제의 onComplete처럼 요청옵션내 onXXXXX로 명명된 프라퍼티/메소드를 간단히 제공하라. 당신이 전달하는 이 함수는 XMLHttpRequest객체 자체가 될 하나의 인자를 가진 객체에 의해 호출될것이다. 당신은 반환 데이터를 얻기 위해 이 객체를 사용할수 있고 아마도 호출의 HTTP결과 코드를 포함할 상태(status) 프라퍼티를 체크할것이다. 몇가지 스크립트나 JSON형태의 데이터를 반환하고자 한다면 X-JSON 헤더가 유용하다.

두개의 다른 흥미로운 옵션은 결과를 처리하기 위해 사용될수 있다. 우리는 AJAX호출이 에러없이 수행될때 호출될 함수처럼 onSuccess옵션을 명시할수 있다. onFailure옵션은 서버에러가 발생할때 호출될 함수가 될수 있다. onXXXXX의 선택적인 함수처럼, 이 두가지는 AJAX호출을 옮기고 X-JSON헤더를 체크하는 XMLHttpRequest를 전달하도록 호출될 것이다.

우리의 샘플은 흥미로운 방법으로 XML응답을 처리하지는 않았다. 우리는 textarea내 XML을 집어넣었다. 응답의 전형적인 사용법은 XML내부에서 바라는 정보를 찾고자 할것이고 몇몇 페이지 요소나 페이지내 HTML을 만드는 몇가지의 XSLT변형을 업데이트할것이다.

1.4.0 버전에서, 이벤트 콜랙 핸들링의 새로운 형태가 소개되었다. 만약 당신이 AJAX호출이 발생하는데도 불구하고 특정 이벤트를 위해 수행되어야 하는 코드를 가지고 있다면, 당신은 새로운 Ajax.Responders 객체를 사용할수 있다.

당신이 AJAX호출이 진행중이라는 시각적 표시를 보여주길 원한다고 해보자. 당신은 두개의 전역 이벤트 핸들러를 사용할수 있다. 하나는 첫번째 호출이 시작되었을때 아이콘을 보여주는것이고 다른 하나는 적어도 하나가 끝났을때 아이콘을 숨기는 것이다. 아래의 예제를 보자.

<script>
	var myGlobalHandlers = {
		onCreate: function(){
			Element.show('systemWorking');
		},

		onComplete: function() {
			if(Ajax.activeRequestCount == 0){
				Element.hide('systemWorking');
			}
		}
	};

	Ajax.Responders.register(myGlobalHandlers);
</script>

<div id='systemWorking'><img src='spinner.gif'>Loading...</div>
	

좀더 완전한 설명을 보기 위해서, Ajax.Request 참조options 참조를 보라..

 

Ajax.Updater 클래스 사용하기

만약 당신이 HTML로 이미 포맷팅된 정보를 반환할수 있는 서버 종료점(endpoint)을 가진다면, 라이브러리는 당신이 Ajax.Updater클래스를 사용하는것을 좀더 쉽게 만들어준다. 이것으로 당신은 어느 요소가 AJAX호출로부터 반환된 HTML을 채우는지 알리게 된다. 예제는 내가 글로 표현하는 것보다 당신을 좀더 쉽게 이해하도록 도와줄것이다.

<script>
	function getHTML()
	{
		var url = 'http://yourserver/app/getSomeHTML';
		var pars = 'someParameter=ABC';
		
		var myAjax = new Ajax.Updater(
			'placeholder', 
			url, 
			{
				method: 'get', 
				parameters: pars
			});
		
	}
</script>

<input type="button" value="GetHtml" onclick="getHTML()"/>
<div id="placeholder"></div>
			

당신이 보는것처럼, 코드는 onComplete함수와 생성자에 전달된 요소 id를 제외하고 이전예제에 비해서 매우 간단하다. 클라이언트에서 서버 에러들을 다루는 것이 어떻게 가능한지 보기 위해 코드를 조금 변경해 보자.

우리는 호출을 위해 더 많은 옵션을 추가하고 에러 상황을 뽑아내기 위해 함수를 명시한다. 이것은 onFailure옵션을 사용하여 수행한다. 우리는 성공적인 작동의 경우에만 활성화될 묶음자(placeholder)를 명시할것이다. 이것을 달성하기 위해, 우리는 간단한 요소 id에서 두개의 프라퍼티(success-모든것이 정상적일때 사용되는, failure-어떤것이 실패일때 사용되는)를 가지는 객체로 첫번째 파라미터를 변경할 것이다. 우리는 예제에서 failure 프라퍼티를 사용하지 않을것이고, onFailure옵션에서 reportError함수를 사용할것이다.

<script>
	function getHTML()
	{
		var url = 'http://yourserver/app/getSomeHTML';
		var pars = 'someParameter=ABC';
		
		var myAjax = new Ajax.Updater(
					{success: 'placeholder'}, 
					url, 
					{
						method: 'get', 
						parameters: pars, 
						onFailure: reportError
					});
		
	}

	function reportError(request)
	{
		alert('Sorry. There was an error.');
	}
</script>

<input type="button" value="GetHtml" onclick="getHTML()"/>
<div id="placeholder"></div>

			

만약 당신의 서버 로직이 HTML마크업 대신에 자바스크립트 코드를 반환한다면, Ajax.Updater객체는 자바스크립트 코드가 될수 있다. 자바스크립트로 응답을 처리하기 위한 객체를 얻기 위해, 당신은 객체 생성자의 마지막 인자로 프라퍼티들의 목록에 evalScripts: true;를 간단히 추가한다. 하지만 여기엔 문제가 있다. 이러한 스크립트 블럭은 페이지의 스크립트에 추가되지 않을것이다. 옵션이름인 evalScripts이 제시하는것처럼, 스크립트는 평가될것이다. 차이점이 무엇일까.? 요청된 URL이 반환하는 것이 무엇인지 추측해보자.

<script language="javascript" type="text/javascript">
	function sayHi(){
		alert('Hi');
	}
</script>

<input type="button" value="Click Me" onclick="sayHi()"/>
			

이 경우 당신이 이전에 이것을 시도했다면 이것이 작동하지 않는것을 알고 있을것이다. 이유는 스크립트 블럭은 평가될것이고 평가된 스크립트는 sayHi 라는 이름의 함수를 생성하지 않을것이다. 이것은 아무것도 하지 않을것이다. 이 함수를 생성하기 위해, 우리는 함수를 생성하기 위해 변경할 필요가 있다. 아래를 보라.

<script language="javascript" type="text/javascript">
	sayHi = function(){
		alert('Hi');
	};
</script>

<input type="button" value="Click Me" onclick="sayHi()"/>
			

이전 예제에서, 우리는 변수를 선언하기 위해 var 키워드를 사용하지 않았다. 그렇게 하는 것은 스크립트 블럭에 지역화될 함수 객체를 생성할것이다. var 키워드 없이 함수 객체는 window범위에서 작동한다.

좀더 상세한 complete설명을 위해서는, Ajax.Updater 참조문서options 참조문서를 보라.

 

What are all those "?" and squares?

So you went and wrote some quick test scripts to update your pages using the Ajax.Updater object and it all worked fine. Life was good until you ran your scripts against real data. All of a sudden the updated text was displayed with question marks or unprintable character symbols where the non-English characters should be.

Your first suspect is prototype.js, Of course, it seemed too easy to be true. But don't blame the library just yet. Ask yourself how much you really understand character encoding, code pages, and how the browser deals with it. If you have a positive answer then I bet you are on your way to fix the problem. If you are among the other 80% (another useless, imprecise author's estimate) of web developers that take character encoding for granted, keep reading.

I won't pretend to be an authority on the topic, much less give you a complete explanation of how this is best handled. Instead you go straight to the solution that I use and provide hints on how this could be fixed in your own scenario.

Simply put, the solution revolves around the following statement: Serve what the browser is expecting you to serve. If we are going to update the page with text that contains Unicode/UTF-8 characters then we better make the browser aware of that.

Let's start with the simple case when you are just updating the page with text from a static HTML file that resides on your server. When you created that file, depending on which text editor you employed, it is very possible that the file was saved in ANSI (or better said, non-Unicode) format. This is the default for many text editors, especially source code editors, because the file size will be smaller and it's rather unusual to edit source code with Unicode characters in it.

Suppose you have the following file named static-content.html on your server. You saved this file saved in ANSI format.

<div>
	Hi there, José. Yo no hablo español.
</div>

Your main page updates itself using something like the snippet below.

<script>
	function updateWithFile(){
		var url = 'static-content.html';
		var pars = '';
		var myAjax = new Ajax.Updater(
				'placeholder', url, 
				{method: 'get', parameters: pars});
	}
</script>
<div id="placeholder">(this will be replaced)</div>
<input id="btn" value="Test With Static File" 
                 onclick="updateWithFile()" type="button"/>

When you click the button the static file is retrieved but the non-English characters are replaced by question marks or some other symbol. The displayed text will look similar to "Hi there, Jos?. Yo no hablo espa?ol." or "Hi there, Jos?Yo no hablo espa?", depending on your browser.

In this case, the solution is straightforward, simply save the static file in an appropriate format. Let's save it in UTF-8 and run the script again (any decent text editor will have an option in the Save As dialog.) You should now see the correct text (if not, your browser may have cached the old version, try using a different file name.)

If the HTML that you are serving is not static, if it is being dynamically generated by some application framework (like ASP.NET, PHP, or even Perl,) make sure the code that generates this HTML is producing the text in the appropriate encoding and code page, and include in the HTTP response headers one header that informs this. Each platform has a different way to achieve this, but they are very similar.

For example, in ASP.NET you can set this globally in your web.config file and the default configuration is good enough to avoid this problem in the first place. You should already have the following section in your web.config.

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

고전적인 ASP 3.0에서 다음의 코드를 사용하여 이 문제를 해결할수 있다.

Response.CodePage = 65001
Response.CharSet = "utf-8" 

PHP에서 응답 헤더를 추가하기 위한 문법은 다음과 같을것이다.

<?php header('Content-Type: text/html; charset=utf-8'); ?>

어떤 경우에는, 당신이 생각하는 목표가 응답 메시지에 다음 HTTP 헤더를 보내는 것이다.

Content-Type: text/html; charset=utf-8 

위 예제에서는 UTF-8을 사용했지만 다른 셋팅이 필요하다면 쉽게 바꿀수 있다.

열거(Enumerating)...

우리는 루프(loop)에 친숙하다. 당신이 알다시피, 배열 자체를 생성하고 같은 종류의 요소로 채운다. 루프 제어구조(이를 테면, foreach, while, repeat 등등)을 생성하고 숫자로 된 인덱스를 통해 순차적으로 각각의 요소에 접근하고 그 요소로 작업을 수행한다.

당신이 이것에 대해 생각할때, 언제나 당신은 코드에 배열을 가지고 루프내 배열을 사용할것이라는것을 의미한다. 이러한 반복을 다루기 위해 좀더 많은 기능을 가진 배열 객체가 있다면 좋지 않겠는가.? 그렇다. 많은 프로그래밍 언어는 배열이나 유사한 구조(collection과 list와 같은)에서 이러한 기능을 제공한다.

prototype.js는 우리에게 반복가능한 데이터를 다룰때 사용하도록 구현된 Enumerable 객체를 제공한다. prototype.js 라이브러리는 더 나아가 Enumerable의 모든 메소드로 Array 클래스를 확장한다

 

루프, 루비-스타일

표준 자바스크립트에서, 당신이 배열의 요소를 순차적으로 표시하길 원한다면, 당신은 다음처럼 작성할수 있다.

<script>
	function showList(){
		var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie'];
		for(i=0;i<simpsons.length;i++){
			alert(simpsons[i]);
		}
	}

</script>

<input type="button" value="Show List" onclick="showList();" /> 
			

prototype.js를 사용하면, 다음과 같이 다시 작성할수 있다.


	function showList(){
		var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie'];
		simpsons.each( function(familyMember){
			alert(familyMember);
		});
	}
			

당신은 특이한 문법으로 별로 좋지않다고 생각할지도 모른다. 위 예제에서, 엉망으로 만드는 것은 아무것도 없다. After all, there's not much to be changed in such a drop-dead-simple example. But keep reading, nonetheless.

each 메소드에 대한 인자처럼 전달되는 이 함수는 보았는가.? iterator 함수처럼 이것을 참조해보자.

 

스테로이드(steroids)에서 당신의 배열

위에서 언급된것처럼, 이것은 같은 프라퍼티와 메소드를 가지는 배열내 모든 요소를 위해 공통이다. 우리의 새로운 배열을 가지고 iterator함수의 장점을 가질수 있는 방법을 보자.

문법에 따르는 요소를 찾아라.

<script>
	function findEmployeeById(emp_id){
		var listBox = $('lstEmployees')
		var options = listBox.getElementsByTagName('option');
		options = $A(options);
		var opt = options.find( function(employee){
			return (employee.value == emp_id);
		});
		alert(opt.innerHTML); //displays the employee name
	}
</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="Find Laura" onclick="findEmployeeById(8);" /> 
			

배열에서 항목을 걸러내는 방법을 보자. 그리고나서 각각의 요소로부터 맴버를 가져온다.

<script>
	function showLocalLinks(paragraph){
		paragraph = $(paragraph);
		var links = $A(paragraph.getElementsByTagName('a'));
		//find links that do not start with 'http'
		var localLinks = links.findAll( function(link){
			//we'll just assume for now that external links
			// do not have a '#' in their url
			return link.href.indexOf('#') >= 0;
		});
		//now the link texts
		var texts = localLinks.pluck('innerHTML');
		//get them in a single string
		var result = texts.inspect();
		alert(result);
	}

</script>
<p id="someText">
	This <a href="http://othersite.com/page.html">text</a> has 
	a <a href="#localAnchor">lot</a> of 
	<a href="#otherAnchor">links</a>. Some are 
	<a href="http://wherever.com/page.html">external</a>
	and some are <a href="#someAnchor">local</a>
</p>
<input type="button" value="Find Local Links" onclick="showLocalLinks('someText')"/>
			

이것은 이 문법에 완전히 빠지도록 하기 위한 몇가지 예제를 가진다. 사용가능한 모든 함수를 위해 Enumerable and Array 참조문서를 보라.

 

내가 강력하게 추천하는 책들.

다음의 책들은 AJAX애플리케이션을 만들기 위해 요구되는 새로운 스킬을 배우는데 많은 도움을 주었고 이미 알고 있던 스킬을 좀더 탄탄하게 만들어주었다. 나는 좋은 책이 충분히 금적적인 가치를 하고 오랜시간동안 가치를 이어간다고 생각한다.

 

prototype.js 참조

JavaScript 클래스에 대한 확장

prototype.js라이브러리에 기능을 추가하기 위한 방법중 하나는 현재 존재하는 JavaScript클래스를 확장하는 것이다.

 

Object 클래스를 위한 확장

메소드 종류 인자 상세설명
extend(destination, source) static destination: 객체, source: 객체 source에서 destination으로 모든 프라퍼티와 메소드를 복사하여 상속을 구현하기 위한 방법을 제공
inspect(targetObj) static targetObj: 객체 targetObj의 사람이 읽을수 있는 문자열 표현으로 반환. 주어진 객체가 inspect 인스턴스 메소드를 정의하지 않는다면, toString 의 값을 반환
keys(targetObj) static targetObj: 객체 모든 프라퍼티의 이름과 주어진 객체의 메소드를 가진 Array를 반환
values(targetObj) static targetObj: 객체 모든 프라퍼티의 값과 주어진 객체의 메소드를 가진 Array를 반환
clone(targetObj) static targetObj: 객체 targetObj의 얕은(shallow) 복사물을 반환

 

Number 클래스를 위한 확장

메소드 종류 인자 상세설명
toColorPart() instance (none) 숫자의 16진법 표현을 반환. 색상의 RGB컴포넌트를 HTML표현으로 변환할때 유용
succ() instance (none) 다음 숫자를 반환. 이 함수는 반복을 포함하는 시나리오에서 사용된다.
times(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 인자 valueindex를 반복적으로 전달하는 iterator 함수를 호출하는 것은 iteration과 현재 index내 현재 값을 각각 포함한다.

다음의 예제는 0에서 9까지의 메시지 박스를 표시할것이다.

<script>
	function demoTimes(){
		var n = 10;
		n.times(function(index){
			alert(index);
		});
		/***************************
		 * you could have also used: 
		 *           (10).times( .... ); 
		 ***************************/
	}

</script>

<input type="button" value="Test Number.times()" onclick="demoTimes()"/>
			

 

Function 클래스를 위한 확장

메소드 종류 인자 상세설명
bind(object [, arg1 [, arg2 [...]]]) instance object: 메소드를 소유하는 객체 함수(=메소드) 소유자 객체로 미리 묶는 함수의 인스턴스를 반환. 반환된 함수는 원래의 것과 같은 인자를 가질것이다.
bindAsEventListener(object [, arg1 [, arg2 [...]]]) instance object: 메소드를 소유하는 객체 유하는 객체 함수(=메소드) 소유자 객체로 미리 묶는 함수의 인스턴스를 반환. 반환된 함수는 이것의 인자로 현재 이벤트 객체를 가질것이다.

실제로 이 확장 중 하나를 보자.

<input type="checkbox" id="myChk" value="1"/> Test?
<script>
	//declaring the class
	var CheckboxWatcher = Class.create();

	//defining the rest of the class implementation
	CheckboxWatcher.prototype = {

	   initialize: function(chkBox, message) {
			this.chkBox = $(chkBox);
			this.message = message;
			//assigning our method to the event
			
			this.chkBox.onclick = 
			   this.showMessage.bindAsEventListener(this, ' from checkbox');
			
	   },

	   showMessage: function(evt, extraInfo) {
		  alert(this.message + ' (' + evt.type + ')' + extraInfo);
	   }
	};


	var watcher = new CheckboxWatcher('myChk', 'Changed');
</script>

			

 

String 클래스를 위한 확장

메소드 종류 인자 상세설명
camelize() instance (none) -(하이픈)으로 분리된 문자열을 camelCaseString으로 변환하기. 이 함수는 예를 들면, 프라퍼티 스타일을 다루는 코드를 작성할때 유용하다.
capitalize() instance (none) 첫번째 글자를 대문자로 변환
dasherize() instance (none) '_' 기호를 '-' 기호로 대체
escapeHTML() instance (none) HTML마크업 문자들이 escaped된 문자열 반환
evalScripts() instance (none) 문자열내에서 발견되는 각각의 <script />블럭을 평가하기
extractScripts() instance (none) 문자열내에서 발견되는 모든 <script />블럭을 포함하는 Array객체 반환
gsub(pattern, replacement) instance pattern: 검색하는 문자열이나 정규 표현식 replacement: 간단한 문자열, 템플릿 문자열 또는 대체물을 만들기 위한 Function(strings[]) 현재 문자열에서 패턴 문자열을 찾은 결과의 문자열을 반환하고 대체 문자열이나 패턴에 일치하는 문자열을 가진 배열을 전달하는 대체함수를 호출한 결과로 대체한다. 대체물이 문자열일때, #{n}과 같은 특별한 템플릿 형태의 토큰을 포함할수 있다. 여기서 n이라는 값은 정규표현식 그룹의 인덱스이다. #{0}는 완전히 일치하면 대체될것이고 #{1}는 첫번째 그룹, #{2}는 두번째이다.
parseQuery() instance (none) toQueryParams()와 같음.
scan(pattern, replacement) instance pattern: 검색하는 문자열이나 정규 표현식. replacement: 반복을 통해 일치하는지 보는 Function(strings[]) 반복을 통해 문자열이 일치하는 패턴을 찾기 위한 방법을 제공한다. pattern인자는 문자열이나 RegExp가 될수 있지만 RegExp는 좀더 유용하다. 유사하게도 replacement인자는 문자열이나 함수가 될수 있지만 유용한것을 만들수 있도록 함수에 전달하는것이 좋다.
strip() instance (none) 문자열의 앞뒤로 공백 없는 문자열을 반환
stripScripts() instance (none) 삭제된 <script /> 블럭을 가진 문자열을 반환
stripTags() instance (none) HTML이나 XML태그가 삭제된 문자열을 반환
sub(pattern, replacement [, count]) instance pattern: 검색하는 문자열이나 정규 표현식. replacement: 문자열 또는 대체물을 만드는 Function(strings[]) count: 숫자나 대체물 - 디폴트는 1 gsub와 매우 유사하지만 count파라미터로 지정되는 대체물의 수에 제한이 있다
toArray() instance (none) 문자열을 이것의 문자들의 Array로 쪼개기
toQueryParams() instance (none) 쿼리문자열(querystring)을 파라미터 이름에 의해 인덱스화되는 결합된 Array로 쪼개기
truncate(length [, truncation]) instance length: 결과 문자열의 최대 길이 truncation: 결과 문자열의 마지막 글자를 대체하기 위해 사용되는 문자열 - 디폴트는 '...' 최대 길이의 문자열을 만들기 위해 사용. 문자열이 최대 길이를 유지하기 위해 짤릴필요가 있을 경우, truncation인자의 텍스트는 마지막의 몇개의 글자를 대체하기 위해 사용된다. (이를테면.: var s='123456790'; alert(s.truncate(5)); //displays '12...' )
underscore() instance (none) CamelizedStringValue를 uderscore_formatted_string로 변환. (이를테면.: var s='Namespace::MyClass123'; alert(s.underscore()); //displays 'namespace/my_class123' ). 이 함수는 루비 온 레일즈 기능에서 직접 대상이 될것처럼 보인다.
unescapeHTML() instance (none) escapeHTML()의 반대

 

Array 클래스를 위한 확장

시작하기 위해, ArrayEnumerable를 확장한다. 그래서 Enumerable객체내에 정의되는 모든 편리한 메소드는 사용가능하다. 이것외에도, 아래의 메소드들이 구현되었다.

메소드 종류 인자 상세설명
clear() instance (none) 배열을 비우고 자체를 반환한다.
compact() instance (none) null 이거나 undefined인 요소를 제외하고 배열을 반환한다. 이 메소드는 배열자체를 변경하지 않는다.
first() instance (none) 배열의 첫번째 요소를 반환한다.
flatten() instance (none) 기복이 없고, 1차원의 배열을 반환한다. 이 함수는 배열이고 반환된 배열내 요소를 포함하는 배열의 각 요소를 찾음으로써 수행된다.
indexOf(value) instance value: what you are looking for. 배열에서 찾아진다면 주어진 value의 0부터 시작하는 인덱스의 위치를 반환. value이 없다면 -1을 반환
inspect() instance (none) 요소를 가진 배열의 잘 포맷팅된 문자열 표시를 반환하기 위해 변경
last() instance (none) 배열의 마지막 요소를 반환한다.
reverse([applyToSelf]) instance applyToSelf: 배열 자체가 반전되는지 표시 역순서로 배열을 반환. 인자가 주어지지 않거나 인자가 true라면, 배열자체는 반전될것이다. 그렇지 않으면 변경되지 않고 남는다.
shift() instance (none) 첫번째 요소를 반환하고 배열로부터 이것을 제거한다. 배열의 길이는 1 감소한다.
without(value1 [, value2 [, .. valueN]]) instance value1 ... valueN: 배열내 존재한다면 제외될 값 인자의 리스트에 포함된 요소를 제외한 배열을 반환. 이 메소드는 배열 자체를 변경하지는 않는다.

이 메소드들을 사용하는 것을 보자.

<script>
var A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
alert(A.inspect()); // "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']"
var B = A.without('e','f');
alert(B.inspect()); // "['a', 'b', 'c', 'd', 'g', 'h']"
alert(A.inspect()); // did not change A: "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']"
A.push(null);
A.push('x');
A.push(null);
A.push('y');
alert(A.inspect()); // "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', null, 'x', null, 'y']"
A = A.compact();
alert(A.inspect()); // "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'y']"
var e = A.shift();
alert(e); // "a" 
alert(A.inspect()); // "['b', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'y']"
alert(A.indexOf('c')); // 1
alert(A.first()); // 'b'
alert(A.last()); // 'y'
A.clear();
alert(A.inspect()); // "[]"
A = ['a', 'b', 'c'];
B = A.reverse(false);
alert(B.inspect()); // "['c', 'b', 'a']"
alert(A.inspect()); // A left untouched: "['a', 'b', 'c']"
A.reverse(true);
alert(A.inspect()); // "['c', 'b', 'a']"	
A = ['a', 'b',  ['c1','c2','c3'] , 'd',  ['e1','e2']  ];
B = A.flatten();
alert(B.inspect()); // "['a','b','c1','c2','c3','d','e1','e2']"		
alert(A.inspect()); // unchanged: "['a','b',['c1','c2','c3'],'d',['e1','e2']]"		
</script>
			

 

document DOM 객체를 위한 확장

메소드 종류 인자 상세설명
getElementsByClassName(className [, parentElement]) instance className: 요소와 연관된 CSS 클래스 이름, parentElement: 객체 또는 가져올 요소를 포함하는 요소의 객체나 id 주어진 CSS 클래스명과 연관된 모든 요소를 반환. parentElement id가 주어졌다면, 전체 문서가 검색될것이다.

 

Event 객체를 위한 확장

프라퍼티 타입 상세설명
KEY_BACKSPACE Number 8: 되돌리기(<-) 키를 위한 상수 코드.
KEY_TAB Number 9: 탭키를 위한 상수코드
KEY_RETURN Number 13: 리턴키를 위한 상수코드
KEY_ESC Number 27: Esc키를 위한 상수코드
KEY_LEFT Number 37: 왼쪽 화살표 키를 위한 상수코드
KEY_UP Number 38: 위쪽 화살표 키를 위한 상수코드
KEY_RIGHT Number 39: 오른쪽 화살표 키를 위한 상수코드
KEY_DOWN Number 40: 아래쪽 화살표 키를 위한 상수코드
KEY_DELETE Number 46: Delete키를 위한 상수코드
observers: Array 캐시된 관찰자(observers)의 목록. 상세한 객체의 내부구현의 일부
메소드 종류 인자 상세설명
element(event) static event: Event객체 이벤트를 일으키는 요소를 반환
isLeftClick(event) static event: Event객체 마우스 왼쪽 버튼을 클릭시 true값 반환
pointerX(event) static event: Event객체 페이지에서 마우스 포인터의 x측 좌표값 반환
pointerY(event) static event: Event객체 페이지에서 마우스 포인터의 y측 좌표값 반환
stop(event) static event: Event객체 이벤트의 디폴트 행위를 취소하고 위임을 연기하기 위해 이 함수를 사용
findElement(event, tagName) static event: Event객체, tagName: 원하는 태그명 DOM트리 위쪽으로 가로지른다. 주어진 태그명을 가진 첫번째 요소를 검색한다. 이벤트를 발생시키는 요소로부터 시작한다.
observe(element, name, observer, useCapture) static element: 객체 또는 아이디, name: 이벤트 명 (like 'click', 'load', etc), observer: 이벤트를 다루는 함수, useCapture: true라면, capture내 이벤트를 다루고 false라면 bubbling 내 이벤트를 다룬다. 이벤트를 위한 이벤트 핸들러 함수를 추가
stopObserving(element, name, observer, useCapture) static element: 객체 또는 아이디, name: 이벤트 명 (like 'click'), observer: 이벤트를 다루는 함수, useCapture: true이면, capture내 이벤트를 다루고 false이면 bubbling 내 이벤트를 다룬다. 이벤트로부터 이벤트 핸들러를 제거
_observeAndCache(element, name, observer, useCapture) static   private메소드, 이것에 대해 걱정하지말라
unloadCache() static (none) private메소드, 이것에 대해 걱정하지말라. 메모리로부터 캐시된 모든 관찰자(observer)를 지운다.

window객체의 이벤트를 로그하기 위한 이벤트 핸들러를 추가하는 객체를 사용하는 방법을 보자.

<script>
	Event.observe(window, 'load', page_loaded, false);

	function page_loaded(evt) {
	  Event.observe('parent_node', 'click', item_clicked, false);
	}
	
	function item_clicked(evt){
		var child = Event.element(evt);
		alert('The child node with id=' + child.id + ' was clicked');
		Event.stop(evt); //avoid another call related to 'parent_node' itself
	}
</script>	
...
<div id="parent_node">
	<div id="child1">First</div>
	<div id="child2">Second</div>
	<div id="child3">Third</div>
</div>		
			

 

prototype.js에 새롭게 정의된 객체와 클래스

라이브러리가 당신을 돕는 다른 방법은 객체지향 디자인과 공통적인 기능을 위한 지원 모두를 구현하는 많은 객체를 제공하는 것이다.

 

PeriodicalExecuter 객체

이 객체는 주어진 함수를 주어진 시간간격으로 반복적으로 호출하기 위한 로직을 제공한다.

메소드 종류 인자 상세설명
[ctor](callback, interval) constructor callback: 오직 인자로 PeriodcalExecuter 객체 자체가 전달될 함수, interval: 초단위 시간간격 함수를 반복적으로 호출할 이 객체의 하나의 인스턴스를 생성
registerCallback() instance (none) 타이머를 다시 셋팅한다.
stop() instance (none) 타이머를 취소하고 콜백 실행을 하지 않도록 한다.
onTimerEvent() instance (none) 타이머가 호출하는 메소드. 순차적으로 객체 자체를 전달하는 콜백 메소드를 호출할것이다.
프라퍼티 타입 상세설명
callback Function(objExecuter) 호출되기 위한 함수. objExecuter: PeriodcalExecuter가 호출을 만든다.
timer Timer 콜백 메소드를 반복적으로 호출하기 위해 타이머 객체를 다룬다.
frequency Number 이것은 수초내 간격으로 실질적으로 작용
currentlyExecuting Boolean 만약 함수 호출이 진행중이라면 표시

 

Prototype 객체

Prototype 객체는 사용되는 라이브러리의 버전을 명시하는 것보다 중요한 역활을 가지지 않는다.

프라퍼티 타입 상세설명
Version String 라이브러리의 버전
emptyFunction Function() 비어있는(empty) 함수 객체
K Function(obj) 주어진 파라미터를 되돌리는 함수 객체
ScriptFragment String 스크립트를 확인하는 정규식 표현

 

Enumerable 객체

Enumerable 객체는 list형태의 구조내에서 항목을 반복하기 위한 좀더 멋진 코드를 작성하는 것을 허용한다.

많은 객체들은 유용한 인터페이스에 영향을 끼치기 위해 Enumerable 을 확장한다.

프라퍼티 타입 상세설명
each(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 주어진 iterator함수를 호출하는 것은 첫번째 인자내 목록으로 각각의 요소와 두번째 인자내 요소의 인덱스 전달한다
all([iterator]) instance iterator: Function(value, index)를 충족하는 함수 객체(선택사항) 이 함수는 주어진 함수를 사용하여 값들의 전체 집합을 테스트하기 위한 방법이다. iterator 함수가 어떤 요소를 위해 falsenull을 반환한다면, all은 false를 반환할것이다. 그렇지 않다면 true를 반환할것이다. iterator가 주어지지 않는다면, 요소 자체가 falsenull이 아닌지 테스트할것이다. 당신은 "모든 요소가 false가 아닌지 체크한다"와 같이 이것을 읽을수 있다.
any([iterator]) instance iterator: Function(value, index)를 충족하는 함수 객체(선택사항) 이 함수는 주어진 함수를 사용하여 값들의 전체 집합을 테스트하기 위한 방법이다. iterator함수가 어떤 요소를 위해 falsenull을 반환하지 않는다면 anytrue를 반환할것이다. 그렇지 않다면 false를 반환할것이다. iterator가 주어지지 않는다면, 요소 자체가 falsenull이 아닌지 테스트할것이다. 당신은 "어느 요소가 false가 아닌지 체크한다"와 같이 이것을 읽을수 있다.
collect(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 각각의 요소를 위한 iterator함수를 호출하고 Array로 각각의 결과를 반환한다. 집합내 각각의 요소를 위한 하나의 결과 요소는 같은 순서이다.
detect(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 각각의 요소를 위한 iterator함수를 호출하고 true를 반환하는 iterator함수를 야기하는 첫번째 요소를 반환한다. true를 반환하는 요소가 없다면, detectnull을 반환한다.
entries() instance (none) toArray()와 같다.
find(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 detect()와 같다.
findAll(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 각각의 요소를 위한 iterator함수를 호출하고 true로 해석되는 값을 반환하는 iterator함수를 야기하는 모든 요소를 가진 Array을 반환한다. 이 함수는 reject()와는 반대의 함수이다.
grep(pattern [, iterator]) instance pattern: 요소를 일치시키기 위해 사용되는 RegExp객체, iterator: Function(value, index)를 충족하는 함수 객체 집합내 각각의 요소의 문자열 값을 pattern 정규표현식에 대해 테스트한다. 함수는 정규표현식에 대응되는 모든 요소를 포함하는 Array 를 반환할것이다. iterator함수가 주어진다면, Array는 대응되는 각각의 요소를 가진 iterator를 호출한 결과를 포함할것이다.
include(obj) instance obj: 객체 집합내 주어진 객체를 찾도록 시도한다. 객체가 찾아진다면, true를 반환하고 찾지 못한다면 false를 반환한다.
inGroupsOf(number, fillWith) instance number: 그룹별 타이머의 수, fillWith: 빈 공간을 채울 필요가 있는 값 첫번째 인자로 지정된 만큼의 항목을 포함하는 그룹별 collection을 반환. 초기 collection의 항목수가 첫번째 인자로 주어진 숫자로 나누어지지 않는다면, 마지막 그룹의 끝에 빈 항목이 null로 채워지거나 두번째 인자값으로 채워진다. 예를 들면, ['a','b','c','d'].inGroupsOf(3,'?')[ ['a','b','c'] , ['d','?','?'] ]를 생성한다.
inject(initialValue, iterator) instance initialValue: 초기화 값처럼 사용되는 객체, iterator: Function(accumulator, value, index)를 충족하는 함수 객체 iterator함수를 사용하여 집합의 모든 요소를 조합한다. 호출된 iterator는 accumulator인자에서 이전 반복의 결과를 전달한다. 첫번째 반복은 accumulator인자내 initialValue를 가진다. 마지막 결과는 마지막 반환값이다.
invoke(methodName [, arg1 [, arg2 [...]]]) instance methodName: 각각의 요소내에서 호출될 메소드의 이름, arg1..argN: 메소드 호출로 전달될 인자. 집합의 각각의 요소내 methodName에 의해 명시되는 메소드를 호출하는 것은 주어진 인자(arg1에서 argN) 전달하고 Array객체로 결과를 반환한다.
map(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 collect()과 같다.
max([iterator]) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 가장 큰 값이나 iterator가 주어진다면 집합내 각각의 요소를 위한 iterator호출의 가장 큰 결과를 반환한다.
member(obj) instance obj: any object include()와 같다.
min([iterator]) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 가장 작은 값을 가진 요소나 iterator가 주어진다면 집합내 각각의 요소를 위한 iterator호출의 가장 작은 결과를 가진 요소를 반환한다.
partition([iterator]) instance iterator: Function(value, index)를 충족하는 함수 객체 두개의 다른 배열을 포함하는 Array를 반환한다. 첫번째 배열은 true를 반환하는 iterator함수를 야기하는 모든 요소를 포함할것이고 두번째 배열은 남아있는 요소를 포함할것이다. 만약 iterator가 주어지지 않는다면, 첫번째 배열은 true로 해석하는 요소를 포함할것이고 다른 배열은 남아있는 요소를 포함할것이다.
pluck(propertyName) instance propertyName : 각각의 요소로부터 읽어들이는 프라퍼티의 이름. 이것은 요소의 인덱스를 포함할수 있다 집합의 각각의 요소내 propertyName에 의해 명시된 프라퍼티에 값을 가져가고 Array객체로 결과를 반환한다.
reject(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 집합내 각각의 요소를 위한 iterator함수를 호출하고 false로 해석하는 값을 반환하는 iterator함수를 야기하는 모든 요소를 가진 Array를 반환한다. 이 함수는 findAll()과는 반대되는 함수이다..
select(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 findAll()과 같다.
sortBy(iterator) instance iterator: Function(value, index)를 충족하는 함수 객체 iterator함수 호출결과를 따르는 정렬된 모든 요소를 가진 Array을 반환.
toArray() instance (none) 집합의 모든 요소를 가지는 Array를 반환.
zip(collection1[, collection2 [, ... collectionN [,transform]]]) instance collection1 .. collectionN: 병합될 목록, transform: Function(value, index)를 충족하는 함수 객체 현재의 집합으로 각각의 주어진 집합을 병합한다. 이 병합 작업은 같은 수의 요소를 가진 새로운 배열을 반환한다. 현재 집합과 각각의 요소가 각각의 병합된 집합으로부터 같은 인덱스를 가진 요소의 배열(이것을 하위 배열이라고 부르자.)이다. transform함수가 주어진다면, 각각의 하위 배열은 반환되기 전에 이 함수에 의해 변형딜것이다. 빠른 예제 : [1,2,3].zip([4,5,6], [7,8,9]).inspect() 는 "[[1,4,7],[2,5,8],[3,6,9] ]" 를 반환한다.

 

Hash 객체

Hash 객체는 hash구조를 구현한다. 이를테면, Key:Value쌍의 집합.

Hash객체내 각각의 항목은 두개의 요소(첫번째는 key, 두번째는 value)를 가진 배열이다. 각각의 항목은 두개의 프라퍼티(keyvalue)를 가진다.

메소드 종류 인자 상세설명
keys() instance (none) 모든 항목의 key를 가진 Array을 반환
values() instance (none) 모든 항목의 value를 가진 Array을 반환
merge(otherHash) instance otherHash: Hash object hash와 전달된 다른 hash를 조합하고 새로운 결과 hash를 반환
toQueryString() instance (none) 쿼리 문자열처럼 포맷팅된 문자열로 hash의 모든 항목을 반환. 이를테면 'key1=value1&key2=value2&key3=value3'
inspect() instance (none) key:value쌍을 가진 hash의 포맷팅된 문자열 표현을 반환하기 위해 변경(오버라이드)

 

ObjectRange 클래스

Enumerable으로부터 상속

상위 경계나 하위 경계로 값들의 범위를 표시

프라퍼티 타입 종류 상세설명
start (any) instance 범위의 시작값
end (any) instance 범위의 마지막값
exclusive Boolean instance 경계자체가 범위의 일부인지 판단
메소드 종류 인자 상세설명
[ctor](start, end, exclusive) constructor start: 시작값, end: 마지막값, exclusive: 경계가 범위내 포함되는가.? 하나의 range객체를 생성한다. start 에서 end로 범위를 지정한다. startend가 같은 타입의 객체이고 succ()메소드를 가져야만 한다.
include(searchedValue) instance searchedValue: 검색할 값 주어진 값이 범위내 값인지 체크. truefalse값을 반환한다.

 

Class 객체

Class 객체는 라이브러리에서 다른 클래스를 선언할때 사용된다. 클래스를 선언할때 이 객체를 사용하는 것은 생성자로 제공되는 initialize()메소드를 지원하기 위한 새로운 클래스를 발생시킨다.

아래의 샘플을 보라.

//declaring the class
var MySampleClass = Class.create();

//defining the rest of the class implementation
MySampleClass.prototype = {

   initialize: function(message) {
		this.message = message;
   },

   showMessage: function(ajaxResponse) {
      alert(this.message);
   }
};	

//now, let's instantiate and use one object
var myTalker = new MySampleClass('hi there.');
myTalker.showMessage(); //displays alert

			
메소드 종류 인자 상세설명
create(*) instance (any) 새로운 클래스를 위한 생성자를 정의

 

Ajax 객체

이 객체는 AJAX기능을 제공하는 많은 다른 클래스를 위한 root와 명명공간(namespace)처럼 제공한다.

프라퍼티 타입 종류 상세설명
activeRequestCount Number instance 진행중인 AJAX요청의 수.
메소드 종류 인자 상세설명
getTransport() instance (none) 새로운 XMLHttpRequest 객체를 반환

 

Ajax.Responders 객체

Enumerable 로 부터 상속되었다

이 객체는 Ajax관련 이벤트가 발생할때 호출될 객체의 목록을 보존한다. 예를 들어, 당신이 AJAX작업을 위한 전역 예외 핸들러를 연결하길 원한다면 이 객체를 사용할수 있다.

프라퍼티 타입 종류 상세설명
responders Array instance 객체의 목록은 AJAX이벤트 알림(notifications)을 위해 등록되었다.
메소드 종류 인자 상세설명
register(responderToAdd) instance responderToAdd: 호출될 메소드를 가진 객체. responderToAdd인자를 전달하는 객체는 AJAX이벤트(이를테면, onCreate, onComplete, onException 등등)처럼 명명된 메소드를 포함해야만 한다. 유사한 이벤트가 발생하면, 적절한 이름을 가진 메소드를 포함하는 모든 등록된 객체가 호출되는 메소드를 가질것이다.
unregister(responderToRemove) instance responderToRemove: list로부터 제거될 객체 responderToRemove 인자로 전달되는 객체는 등록된 객체의 list로부터 제거될것이다.
dispatch(callback, request, transport, json) instance callback: 보고되는 AJAX이벤트 이름, request: 이벤트를 책임지는 the Ajax.Request 객체, transport: AJAX호출을 가지는 XMLHttpRequest 객체, json: 응답의 X-JSON 헤더(존재할때만) 등록된 객체의 목록을 통해 실행하는 것은 callback 인자내 결정된 메소드를 가지는 것을 찾는다. 호출되는 각각의 메소드는 다른 3개의 인자를 전달한다. AJAX응답이 몇몇 JSON컨텐츠를 가지는 X-JSON HTTP 헤더를 포함한다면, 이것은 평가되고 json인자로 전달될것이다. 만약 이벤트가 onException라면, transport인자는 대신에 예외를 가질것이고 json은 전달되지 않을것이다.

 

Ajax.Base 클래스

이 클래스는 Ajax객체내 정의된 다른 대부분의 클래스를 위한 기본(base)클래스처럼 사용된다.

메소드 종류 인자 상세설명
setOptions(options) instance options: AJAX 옵션 AJAX작업을 위해 필요한 옵션 셋팅
responseIsSuccess() instance (none) 만약 AJAX작업이 성공한다면 true를 반환하고, 실패한다면 false를 반환
responseIsFailure() instance (none) responseIsSuccess()와는 반대.

 

Ajax.Request 클래스

Ajax.Base로 부터 상속

AJAX 작업을 캡슐화

프라퍼티 타입 종류 상세설명
Events Array static AJAX작업중 보고되는 가능한 이벤트/상태의 목록. 목록은 'Uninitialized', 'Loading', 'Loaded', 'Interactive', 그리고 'Complete.'를 포함한다.
transport XMLHttpRequest instance AJAX작업을 가지는 XMLHttpRequest 객체
url String instance 요청에 의해 대상이 되는 URL
메소드 종류 인자 상세설명
[ctor](url, options) constructor url: 꺼내기 위한 url, options: AJAX 옵션 주어진 옵션을 사용하여 주어진 url을 호출할 이 객체의 하나의 인스턴스를 생성. 중요사항: 선택된 url은 브라우저의 보안 셋팅을 위한 대상이 될 가치가 없다. 많은 경우 브라우저는 현재 페이지처럼 같은 호스트로부터가 아니라면 url을 가져오지 않을것이다. 당신은 설정을 피하거나 사용자의 브라우저를 제한하기 위한 로컬 url만을 사용할 것이다.
evalJSON() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 AJAX응답내 존재하는 X-JSON HTTP헤더의 컨텐츠를 평가하기 위해 내부적으로 호출된다.
evalResponse() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. AJAX응답이 text/javascriptContent-type헤더를 가진다면, 응답 몸체는 평가되고 이 메소드는 사용될것이다.
header(name) instance name: HTTP header name 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 AJAX응답의 HTTP헤더의 컨텐츠를 가져오기 위해 내부적으로 호출된다.
onStateChange() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 AJAX호출 상태 변경시 객체 자체에 의해 호출된다.
request(url) instance url: url for the AJAX call 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 생성자를 호출하는 동안 벌써 호출되었다.
respondToReadyState(readyState) instance readyState: 상태 숫자값(1 에서 4) 이 메소드는 대개 외부에서 호출되지 않는다. 이것은 AJAX호출 상태가 변경될때 객체 자체에 의해 호출된다.
setRequestHeaders() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 HTTP요청을 하는 동안 보내어질 HTTP헤더를 조합하기 위한 객체 스스로에 의해 호출된다.

 

options 인자 객체

AJAX작업의 중요한 부분은 options 인자이다. 이것은 기대되는 프라퍼티를 가지는 동안 어떠한 객체도 전달될수 있다. 이것은 AJAX호출을 위해 익명 객체를 생성하는 것이 공통적이다.

프라퍼티 타입 디폴트 상세설명
method String 'post' HTTP요청의 메소드
parameters String '' 요청에 전달한 값들의 url형태의 목록
asynchronous Boolean true AJAX호출이 비동기적으로 만들어지는지 표시
postBody String undefined HTTP POST의 경우 요청의 몸체내 전달되는 내용
requestHeaders Array undefined 요청과 함께 전달되기 위한 HTTP헤더의 목록. 이 목록은 많은 수의 항목을 가져야 한다. 나머지 항목은 사용자 정의 헤더의 이름이다. 그리고 다음의 항목은 헤더의 문자열 값이다. 예제 : ['my-header1', 'this is the value', 'my-other-header', 'another value']
onXXXXXXXX Function(XMLHttpRequest, Object) undefined 각각의 이벤트/상태가 AJAX호출이 발생하는 동안 도착할때 호출될 사용자정의 함수. 이 옵션에는 "XXXXXXXX"를 위해 Ajax.Request.Events, 와 HTTP status codes의 상태중에 다양한 대안이 있다. 예를 들어 var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. 사용되는 함수는 AJAX작업과 평가된 X-JSON응답 HTTP헤더를 포함하는 인자를 가지는 XMLHttpRequest객체를 포함하는 하나의 인자를 받을것이다.
onSuccess Function(XMLHttpRequest, Object) undefined AJAX호출이 성공적으로 완성될때 호출될 사용자정의 함수. 사용되는 함수는 AJAX작업을 가지는 XMLHttpRequest객체를 포함하는 하나의 인자를 받을것이다.
onFailure Function(XMLHttpRequest, Object) undefined AJAX호출이 에러를 가진채 끝날때 호출될 사용자정의 함수. 사용되는 함수는 AJAX작업을 가지는 XMLHttpRequest객체를 포함하는 하나의 인자를 받을것이다.
onException Function(Ajax.Request, exception) undefined 유효하지 않은 응답이나 유효하지 않은 인자와 같이 예외적인 조건이 클라이언트 측 AJAX호출에서 발생했을때 호출될 사용자정의 함수. 사용된 함수는 AJAX작업을 포장하는 Ajax.Request 객체와 exception객체를 포함하는 두개의 인자를 받을것이다.
insertion an Insertion class undefined 새로운 내용이 삽입될 방법을 판단할 클래스. Insertion.Before, Insertion.Top, Insertion.Bottom, 또는 Insertion.After가 될수 있다. Ajax.Updater객체에만 적용한다.
evalScripts Boolean undefined, false 스크립트 블럭이 응답이 도착했을때 평가할지를 판단. Ajax.Updater객체에만 적용 objects.
decay Number undefined, 1 Ajax.PeriodicalUpdater 객체는 받은 응답이 마지막 것과 같을때 비율을 새롭게 하여 연속적인 후퇴를 결정. 예를 들어, 당신이 2를 사용한다면, 새롭게 된것중에 하나가 이전것과 같은 결과를 만든후에, 객체는 다음 refresh를 위한 시간의 두배를 기다릴것이다. 이것은 다시 반복한다면, 객체는 4배를 기다릴것이다. 이것을 후퇴를 피하기 위해 정의되지 않거나 1을 사용하도록 남겨두라.
frequency Number undefined, 2 초단위의 갱신간격(횟수가 아닌), Ajax.PeriodicalUpdater객체에만 적용.

 

Ajax.Updater 클래스

Ajax.Request로 부터 상속

요청된 url이 당신 페이지의 특정 요소내 직접적으로 삽입하길 원하는 HTML을 반환할때 사용된다. 당신은 url이 도착을 평가할 <script>블럭을 반환할때 이 객체를 사용할수 있다. 스크립트로 작업하기 위해 evalScripts 옵션을 사용하라.

프라퍼티 타입 종류 상세설명
containers Object instance 이 객체는 두개의 프라퍼티(containers.success 는 AJAX호출이 성공할때 사용될것이다. 그리고 AJAX호출이 실패한다면 containers.failure가 사용될것이다.)를 포함한다.
메소드 종류 인자 상세설명
[ctor](container, url, options) constructor container: 이것은 요소의 id, 요소객체 자체, 또는 두개의 프라퍼티(AJAX호출이 성공했을때 사용될 object.success 요소(또는 id), 그리고 AJAX호출이 실패했을때 사용될 object.failure요소(또는 id))를 가지는 객체가 될수 있다. url: 가져오기 위한 url, options: AJAX 옵션 주어진 옵션을 사용하여 주어진 url을 호출할 이 객체의 하나의 인스턴스를 생성.
updateContent() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 응답을 받았을때 객체 자체에 의해 호출된다. 이것은 HTML로 적절한 요소를 수정하거나 insertion옵션내 전달되는 함수를 호출할것이다. 이 함수는 두개의 인자(수정되기 위한 요소와 응답 텍스트)를 가지고 호출될것이다.

 

Ajax.PeriodicalUpdater 클래스

Ajax.Base로 부터 상속

이 클래스는 반복적으로 인스턴스화하고 페이지에서 요소를 새롭게 하거나 Ajax.Updater가 수행할수 있는 다른 작업중 어느것을 수행하기 위한 Ajax.Updater객체를 사용한다. 좀더 많은 정보를 위해 Ajax.Updater 참조를 체크하라.

프라퍼티 타입 종류 상세설명
container Object instance 이 값은 Ajax.Updater생성자에 일관적으로 전달될것이다.
url String instance 이 값은 Ajax.Updater의 생성자에 일관적으로 전달될것이다.
frequency Number instance 초단위의 refresh간격. 디폴트는 2초. 이 숫자는 Ajax.Updater 객체를 호출할때 현재 축소(decay)에 의해 곱해질것이다.
decay Number instance 작업을 재-수행할때 적용될 축소(decay)레벨을 유지
updater Ajax.Updater instance 가장 최신에 사용된 Ajax.Updater 객체
timer Object instance 다른 refresh를 위한 시각일때 객체를 알리기 위해 사용되는 자바스크립트 타이머.
메소드 종류 인자 상세설명
[ctor](container, url, options) constructor container:이것은 요소의 id, 요소객체 자체, 또는 두개의 프라퍼티(AJAX호출이 성공할때 사용될 object.success 요소(나 id), AJAX호출이 실패할때 사용할 object.failure 요소(나 id))를 가지는 객체가 될수 있다. url: 가져오기 위한 url, options: AJAX 옵션 주어진 옵션을 사용하여 주어진 url을 호출할 이 객체의 하나의 인스턴스를 생성
start() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것의 정기적인 작업 수행을 시작하기 위해 객체 자체에 의해 호출된다.
stop() instance (none) 주기를 가지는 작업 수행을 종료하도록 한다. 종료후, 객체는 onComplete 옵션에 주어진 콜백을 호출할것이다.
updateComplete() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 요청을 완성한 후에 사용되는 Ajax.Updater에 의해 호출된다. 이것은 다음 refresh스케줄링 하기 위해 사용된다.
onTimerEvent() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 다음 수정을 위한 시각일때 내부적으로 호출된다.

 

Element 객체

이 객체는 DOM내 요소를 변경하기 위해 몇몇 유틸리티성 함수들을 제공한다.

메소드 종류 인자 상세설명
addClassName(element, className) instance element: element 객체 또는 아이디, className: CSS 클래스명 주어진 class명을 요소의 class명으로 추가
classNames(element) instance element: element 객체 또는 아이디 주어진 element와 관련된 CSS 클래스명을 표시하는 Element.ClassNames 객체를 반환
cleanWhitespace(element) instance element: element 객체 또는 아이디 요소의 자식노드에서 공백을 제거
empty(element) instance element: element 객체 또는 아이디 element태그가 비어있는지(또는 공백만을 가지고 있는지) 표시하는 Boolean값을 반환
getDimensions(element) instance element: element 객체 또는 아이디 element의 면적(dimensions)을 반환. 반환된 값은 두개의 프라퍼티(heightwidth)를 가지는 객체이다.
getHeight(element) instance element: element 객체 또는 아이디 요소의 offsetHeight값을 반환
getStyle(element, cssProperty) instance element: element 객체 또는 아이디, cssProperty : CSS프라퍼티('prop-name' 또는 'propName' 가 작동하는 형태)의 이름 주어진 element내 CSS프라퍼티의 값을 반환하거나 존재하지 않는다면 null 을 반환
hasClassName(element, className) instance element: element 객체 또는 아이디, className: CSS 클래스명 요소가 class명중에 하나로 주어진 class명을 가진다면 true를 반환
hide(element) instance element: element 객체 또는 아이디 style.display'none'로 셋팅하여 각각의 요소를 숨긴다.
makeClipping(element) instance element: element 객체 또는 아이디
makePositioned(element) instance element: element 객체 또는 아이디 element의 style.position'relative'로 변경
remove(element) instance element: element 객체 또는 아이디 문서로 부터 요소를 제거한다.
removeClassName(element, className) instance element: element 객체 또는 아이디, className: CSS 클래스명 요소의 class명으로 부터 주어진 class명을 제거
scrollTo(element) instance element: element 객체 또는 아이디 창을 element위치로 스크롤
setStyle(element, cssPropertyHash) instance element: element 객체 또는 아이디, cssPropertyHash : 적용되기 위한 스타일을 가지는 Hash객체 cssPropertyHash 인자내 값에 따라, 주어진 element내 CSS프라퍼티의 값을 셋팅.
show(element) instance element: element 객체 또는 아이디 style.display''로 다시 셋팅하여 각각의 요소를 보여준다.
toggle(element) instance element: element 객체 또는 아이디 각각의 전달된 요소의 가시성(visibility)을 토글(toggle)한다.
undoClipping(element) instance element: element 객체 또는 아이디
undoPositioned(element) instance element: element 객체 또는 아이디 element의 style.position''으로 초기화
update(element, html) instance element: element 객체 또는 아이디, html: html content 주어진 html인자를 가지는 요소의 내부 html을 대체. 주어진 html이 <script>블럭을 포함한다면, 그것들은 포함되지는 않지만 평가될것이다.
visible(element) instance element: element 객체 또는 아이디 요소가 눈에 보이는지 표시하는 Boolean값을 반환

 

Element.ClassNames 클래스

Enumerable로 부터 상속

element에 관련된 CSS 클래스명의 collection을 표시

메소드 종류 인자 상세설명
[ctor](element) constructor element: any DOM element 객체 또는 아이디 주어진 element의 CSS 클래스명을 표시하는 Element.ClassNames 객체를 생성
add(className) instance className: CSS 클래스 명 element에 관련된 class명의 리스트에 주어진 CSS 클래스명을 추가
remove(className) instance className: CSS 클래스 명 element에 관련된 class명의 리스트로부터 주어진 CSS 클래스명을 제거
set(className) instance className: CSS 클래스 명 주어진 CSS 클래스명을 가진 element을 결합, element로부터 다른 class명을 제거.

 

Abstract 객체

이 객체는 라이브러리내 다른 클래스를 위한 root처럼 제공한다. 이것은 어떤 프라퍼티나 메소드도 가지지 않는다. 이 객체에 정의된 클래스는 전통적인 추상 클래스처럼 처리된다.

 

Abstract.Insertion 클래스

이 클래스는 동적으로 내용물을 추가할 다른 클래스를 위한 기본 클래스처럼 사용된다. 이 클래스는 추상 클래스처럼 사용된다.

메소드 종류 인자 상세설명
[ctor](element, content) constructor element: element 객체 또는 아이디, content: 삽입되는 HTML 동적 내용물 삽입을 도울 객체를 생성
contentFromAnonymousTable() instance (none)
프라퍼티 타입 종류 상세설명
adjacency String static, parameter 내용물이 주어진 요소에 대해 상대적으로 위치할 지점을 명시하는 파라미터. 가능한 값은 'beforeBegin', 'afterBegin', 'beforeEnd', 그리고 'afterEnd'.
element Object instance 삽입이 상대적으로 만들어질 요소객체
content String instance 삽입될 HTML

 

Insertion 객체

이 객체는 라이브러리내 다른 클래스를 위한 root처럼 제공한다. 이것은 어떠한 프라퍼티나 메소드를 가지지 않는다. 이 객체에 정의된 클래스는 전통적인 추상 클래스처럼 처리된다.

 

Insertion.Before 클래스

Abstract.Insertion로 부터 상속

요소 앞에 HTML삽입

메소드 종류 인자 상세설명
[ctor](element, content) constructor element: element 객체 또는 아이디, content: 삽입되는 HTML Abstract.Insertion으로 부터 상속. 동적으로 내용물을 삽입하는 것을 돕는 객체를 생성

다음의 코드는

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>

<script> new Insertion.Before('person', 'Chief '); </script>
			

다음처럼 HTML이 변경될것이다.


<br/>Hello, Chief <span id="person" style="color:red;">Wiggum. How's it going?</span>	
			

 

Insertion.Top 클래스

Abstract.Insertion로 부터 상속

요소아래의 첫번째 자식으로 HTML을 삽입. 이 내용물은 요소의 열기 태그뒤에 위치할것이다.

메소드 종류 인자 상세설명
[ctor](element, content) constructor element: element 객체 또는 아이디, content: 삽입되는 HTML Abstract.Insertion으로부터 상속. 동적으로 내용물을 삽입하는 것을 돕는 객체 생성

다음의 코드는

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>

<script> new Insertion.Top('person', 'Mr. '); </script>
			

다음처럼 HTML이 변경될것이다.

<br/>Hello, <span id="person" style="color:red;">Mr. Wiggum. How's it going?</span>	
			

 

Insertion.Bottom 클래스

Abstract.Insertion로 부터 상속

요소아래의 마지막 자식으로 HTML삽입. 내용물은 요소의 닫기 태그앞에 위치할것이다.

메소드 종류 인자 상세설명
[ctor](element, content) constructor element: element 객체 또는 아이디, content: 삽입되는 HTML Abstract.Insertion로 부터 상속. 동적으로 내용물을 삽입하는 것을 돕는 객체 생성

다음의 코드는

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>

<script> new Insertion.Bottom('person', " What's up?"); </script>
			

다음처럼 HTML이 변경될것이다.

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going? What's up?</span>	
			

 

Insertion.After 클래스

Abstract.Insertion로 부터 상속

요소의 닫기 태그뒤 HTML삽입

메소드 종류 인자 상세설명
[ctor](element, content) constructor element: element 객체 또는 아이디, content: 삽입되는 HTML Abstract.Insertion으로부터 상속. 동적으로 내용물을 삽입하는 것을 돕는 객체 생성

다음의 코드는

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>

<script> new Insertion.After('person', ' Are you there?'); </script>
			

다음처럼 HTML이 변경될것이다.

<br/>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> Are you there?	
			

 

Field 객체

This object provides some utility functions for working with input fields in forms.

메소드 종류 인자 상세설명
activate(field) instance field: field element 객체 또는 아이디 포커스를 이동하고 텍스트 선택을 지원하는 field내 값을 선택
clear(field) instance field: field element 객체 또는 아이디 field요소로부터 각각 전달된 값을 지움(clear)
disable(field) instance field: field element 객체 또는 아이디 폼 필드 요소를 사용하지 못하도록 만든다. 요소 객체를 반환한다.
enable(field) instance field: field element 객체 또는 아이디 폼 필드 요소를 사용가능하도록 만든다. 요소 객체를 반환한다.
focus(field) instance field: field element 객체 또는 아이디 주어진 폼 field로 입력 포커스 이동
getValue(field) instance field: field element 객체 또는 아이디 필드에 입력되거나 선택된 값을 반환한다.
present(field) instance field: field element 객체 또는 아이디 모든 폼 field가 빈값이 아니라면 true를 반환
select(field) instance field: field element 객체 또는 아이디 텍스트 선택을 지원하는 field내 값을 선택

 

Form 객체

이 객체는 데이터 항목 폼과 그것들의 입력 field와 작동하기 위한 몇몇 유틸리티성 함수를 제공한다.

메소드 종류 인자 상세설명
serialize(form) instance form: form element 객체 또는 아이디 'field1=value1&field2=value2&field3=value3'처럼 field명과 값의 url형태의 목록을 반환
findFirstElement(form) instance form: form element 객체 또는 아이디 form에서 첫번째로 사용가능한 필드 element를 반환
getElements(form) instance form: form element 객체 또는 아이디 폼내 모든 입력 field를 포함하는 Array 반환
getInputs(form [, typeName [, name]]) instance form: form element 객체 또는 아이디, typeName: input요소의 타입, name: input요소명. 폼내 모든 <input>요소를 포함하는 Array 반환. 선택적으로 목록은 요소의 type이나 name속성에 의해 필터링 될수 있다.
disable(form) instance form: form element 객체 또는 아이디 폼내 모든 입력 field를 사용불가상태로 만들기
enable(form) instance form: form element 객체 또는 아이디 폼내 모든 입력 field를 사용가능하게 만들기
focusFirstElement(form) instance form: form element 객체 또는 아이디 첫번째 가시성을 활성화하고, 폼내 입력 field를 가능하게 하기
reset(form) instance form: form element 객체 또는 아이디 폼을 리셋하기. form객체의 reset()메소드와 같다.

 

Form.Element 객체

이 객체는 폼요소와 작동하기 위한 몇몇 유틸리티성 함수를 제공한다.

메소드 종류 인자 상세설명
serialize(element) instance element: element 객체 또는 아이디 'elementName=elementValue'처럼 요소의 name=value 짝을 반환
getValue(element) instance element: element 객체 또는 아이디 요소의 값을 반환

 

Form.Element.Serializers 객체

이 객체는 폼요소의 현재 값을 가져오기 위해 라이브러리 내부적으로 사용되는 몇몇 유틸리티성 함수를 제공한다.

메소드 종류 인자 상세설명
inputSelector(element) instance element: radio 버튼이나 checkbox처럼 checked프라퍼티를 가지는 form요소의 객체 또는 아이디 ['elementName', 'elementValue']처럼 요소의 이름과 값을 가지는 Array을 반환
textarea(element) instance element: textbox, button 또는 password필드처럼 value프라퍼티를 가지는 form요소의 객체 또는 아이디. ['elementName', 'elementValue']처럼 요소의 이름과 값을 가지는 Array를 반환
select(element) instance element: <select> 요소의 객체 또는 아이디 ['elementName', 'selOpt1 selOpt4 selOpt9']처럼 요소의 이름과 모든 선택된 옵션의 값이나 텍스트를 가지는 Array를 반환

 

Abstract.TimedObserver 클래스

이 클래스는 값이 변경(또는 프라퍼티가 클래스정의를 얻어내는)될때까지 하나의 요소를 모니터링할 다른 클래스를 위한 기본클래스처럼 사용된다. 이 클래스는 추상클래스처럼 사용된다.

하위클래스는 요소의 입력값, style프라퍼티중 하나, 또는 테이블내 row의 수, 또는 당신이 추적하고자 하는 모든것을 모니터링하기 위해 생성될수 있다.

메소드 종류 인자 상세설명
[ctor](element, frequency, callback) constructor element: element 객체 또는 아이디, frequency: 초단위 간격, callback: 요소가 변경될때 호출되는 함수 요소를 모니터링할 객체 생성
getValue() instance, abstract (none) 클래스는 요소에서 모니터링이 되는 현재값이 무엇인지 판단하기 위햔 메소드를 구현해야만 한다.
registerCallback() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 요소 모니터링릉 시작하기 위한 객체 자체에 의해 호출된다.
onTimerEvent() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 요소를 체크하기 위해 정기적으로 객체 자체에 의해 호출된다.
Property Type Description
element Object 모니터링되는 요소객체.
frequency Number 이것은 체크사이에 초단위 간격으로 이루어진다.
callback Function(Object, String) 요소가 변경될때마다 호출되기 위한 함수. 이것은 요소객체와 새로운 값을 받을것이다.
lastValue String 요소내 확인되는 마지막 값

 

Form.Element.Observer 클래스

Abstract.TimedObserver로 부터 상속

폼 입력 요소의 값을 모니터링하는 Abstract.TimedObserver의 구현물. 값 변경을 보고하는 이벤트를 드러내지 않는 요소를 모니터링하고자 할때 이 클래스를 사용하라. 이 경우 당신은 Form.Element.EventObserver 클래스를 대신 사용할수 있다.

메소드 종류 인자 상세설명
[ctor](element, frequency, callback) constructor element: element 객체 또는 아이디, frequency: 초단위 간격, callback: 요소가 변경될때 호출되는 함수 Abstract.TimedObserver으로부터 상속. 요소의 value프라퍼티를 모니터링할 객체를 생성.
getValue() instance (none) 요소의 값을 반환

 

Form.Observer 클래스

Abstract.TimedObserver로 부터 상속

폼내 데이터 항목 요소의 값이 변경하는지를 모니터링하는 Abstract.TimedObserver의 구현물. 당신이 값 변경을 보고하는 이벤트를 드러내지 않는 요소를 포함하는 폼을 모니터링하고자 할때 이 클래스를 사용하라. 이 경우 당신은 Form.EventObserver 클래스를 대신 사용할수 있다.

메소드 종류 인자 상세설명
[ctor](form, frequency, callback) constructor form: form 객체 또는 아이디, frequency: 초단위 간격, form내 데이터 항목 요소가 변경될때 호출되는 콜백 함수 Abstract.TimedObserver로부터 상속. 변경하기 위한 폼을 모니터링할 객체 생성.
getValue() instance (none) 모든 폼의 데이터의 직렬화를 반환

 

Abstract.EventObserver 클래스

이 클래스는 요소를 위해 값-변경 이벤트가 발생할때마다 콜백함수를 수행하는 다른 클래스를 위한 기본 클래스처럼 사용된다.

Abstract.EventObserver 타입의 다중 객체는 다른것을 지우지 않고 같은 요소로 묶일수 있다. 콜백은 요소에 할당되는 순서대로 수행될것이다.

트리거 형태의 이벤트는 radio버튼과 checkbox를 위해서는 onclick이고 대개의 textbox와 리스트박스/드랍다운을 위해서는 onchange이다.

메소드 종류 인자 상세설명
[ctor](element, callback) constructor element: element 객체 또는 아이디, callback: function to be called when the event happens 요소를 모니터링할 객체 생성.
getValue() instance, abstract (none) 클래스는 요소에서 모니터링이 되는 현재값이 무엇인지 판단하기 위햔 메소드를 구현해야만 한다.
registerCallback() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 요소의 이벤트를 자체적으로 묶는 객체에 의해 호출된다.
registerFormCallbacks() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 폼내 각각의 데이터 항목 요소의 이벤트로 자체적으로 묶기 위한 객체에 의해 호출된다.
onElementEvent() instance (none) 이 메소드는 대개 외부적으로 호출되지 않는다. 이것은 요소의 이벤트로 묶일것이다.
프라퍼티 타입 상세설명
element Object 모니터링되는 요소객체
callback Function(Object, String) 요소가 변경될때마다 호출되기 위한 함수. 이것은 요소객체와 새로운 값을 받을것이다.
lastValue String 요소내 확인되는 마지막 값

 

Form.Element.EventObserver 클래스

Abstract.EventObserver로 부터 상속

요소내 값 변경을 감지하기 위한 폼 데이터 항목 요소의 적절한 이벤트를 위한 콜백 함수를 수행하는 Abstract.EventObserver의 구현물. 만약 요소가 변경을 보고하는 이벤트를 드러내지 않는다면, 당신은 Form.Element.Observer 클래스를 대신 사용할수 있다.

메소드 종류 인자 상세설명
[ctor](element, callback) constructor element: element 객체 또는 아이디, callback: 이벤트가 발생할때 호출될 함수 Abstract.EventObserver로 부터 상속. 요소의 value프라퍼티를 모니터링할 객체 생성.
getValue() instance (none) 요소의 값 반환

 

Form.EventObserver 클래스

Abstract.EventObserver로 부터 상속

값이 변결될때 감지하기 위한 요소의 이벤트를 사용하여 폼내 포함되는 어느 데이터 항목 요소에 변경을 모니터링하는 Abstract.EventObserver의 구현물. 만약 폼이 변경을 보고하는 이벤트를 드러내지 않는 요소를 포함한다면, 당신은 Form.Observer 클래스를 대신 사용할수 있다.

메소드 종류 인자 상세설명
[ctor](form, callback) constructor form: form 객체 또는 아이디, callback: form내 데이터 항목 요소가 변경될때 호출되는 함수 Abstract.EventObserver로부터 상속. 변경을 위해 폼을 모니터링할 객체 생성.
getValue() instance (none) 모든 폼의 데이터 직렬화를 반환.

 

Position 객체 (예비 문서)

이 객체는 요소 위치할당을 작업할때 돕는 수많은 함수를 제공한다.

메소드 종류 인자 상세설명
prepare() instance (none) 스크롤 위치내 변경을 수용하기 위한 deltaXdeltaY 프라퍼티 조정. 페이지 스크롤후 withinIncludingScrolloffset를 호출하기 전에 이 메소드를 호출하는 것을 기억하라.
realOffset(element) instance element: object 요소에 영향을 끼치는 어느 스크롤 offset를 포함하는 요소의 정확한 스크롤 offset를 가진 Array을 반환. 이 결과 배열은 [total_scroll_left, total_scroll_top]과 유사하다.
cumulativeOffset(element) instance element: object 위치가 할당된 부모 요소에 의해 부과된 어느 offset를 포함하는 요소의 정확한 위치가 할당된 offset를 가진 Array을 반환. 결과 배열은 [total_offset_left, total_offset_top]과 유사하다.
within(element, x, y) instance element: object, x 와 y: 위치 조정 만약 주어진 지점이 주어진 요소의 직사각형내 조정이 되는지 테스트
withinIncludingScrolloffsets(element, x, y) instance element: object, x and y: coordinates of a point  
overlap(mode, element) instance mode: 'vertical' or 'horizontal', element: object within()은 이 메소드가 호출되기 전에 호출될 필요가 있다. 이 메소드는 요소에서 겹치는 것을 조정하는 세분화정도를 표현하는 0.0과 1.0사이의 10진수를 반환할것이다. 예를 들면, 만약 요소가 100px를 가지는 정사각형 DIV이고 (300,300)에 위치한다면, within(divSquare, 330, 330); overlap('vertical', divSquare);는 0.70을 반환해야만 한다. 이 값이 의미하는 것은 DIV의 아래쪽 경계에서 70%(100px - 30px = 70px)를 표시하는 지점이라는 것이다. 이해하기 가장 쉬운 방법은 다른 사각형의 위-왼쪽 구석처럼 주어진 쌍을 생각하는 것이다. 숫자값은 겹치는 넓이와 높이의 퍼센트값일 것이다.
clone(source, target) instance source: element 객체 또는 아이디, target: element 객체 또는 아이디 source요소에 대해 똑같이 target요소의 크기를 다시 조정하고 다시 위치를 지정

1.5.0을 위한 이 문서는 여전히 작업중입니다. 이 문서의 업데이트를 계속 지켜봐주십시오.
만약 에러를 발견한다면, 나에게 알려주십시오. 그러면 가능한 한 빨리 그것을 수정할것입니다.
한글 번역에 관련된 부분은 한국어 번역자으로 알려주십시오.

출처 : http://hitnrun21.tistory.com/20?srchid=BR1http%3A%2F%2Fhitnrun21.tistory.com%2F20

+ Recent posts