컴퓨터잡담

Prototype.js를 제대로 사용하는 방법

by 디케 posted Mar 27, 2010
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

id로 특정 요소 가져오기[#1]

이전의 방법
document.getElementById('foo')

추천하는 방법

$('foo')

폼 컨트롤러의 값을 가져오기[#2]

var woot = document.getElementById('bar').value
var woot = $('bar').value

추천하는 방법

var woot = $F('bar')

스타일 변경하기[#3]

이전의 방법
$('footer').style.height = '100px';
$('footer').style.background = '#ffc';  

추천하는 방법

$('footer').setStyle({
  height: '100px',
  background: '#ffc'
})

html 내용 변경하기[#4]

이전의 방법
$('coolestWidgetEver').innerHTML = 'some nifty content'

추천하는 방법

$('coolestWidgetEver').update('some nifty content')

Ajax Request의 파라미터 셋팅하기[#5]

이전의 방법
new Ajax.Request('ninja.php?weapon1=foo&weapon2=bar')

추천하는 방법

new Ajax.Request('ninja.php', {
  parameters: {
    weapon1: 'foo',
    weapon2: 'bar'
  }
})

Ajax Request 생성하기[#6]

이전의 방법
new Ajax.Request('blah.php', {
  method: 'POST',
  asynchronous: true,
  contentType: 'application/x-www-form-urlencoded',
  encoding: 'UTF-8',
})

추천하는 방법

new Ajax.Request('blah.php')

여기서 위 방법이 잘못된게 아니다. 하지만 사용된 값이 모두 디폴트 값이기 때문에 굳이 표기할 필요가 없다는 것이다.

Event 추가하기[#7]

이전의 방법
Event.observe('myContainer', 'click', doSomeMagic)

추천하는 방법

$('myContainer').observe('click', doSomeMagic)

뒤의 방법이 좀더 객체 지향적이고 다른 이벤트를 추가하기가 용이하다.

각 요소별로 함수 실행하기[#8]

이전의 방법
$$('div.hidden').each(function(el){
  el.show();
})

추천하는 방법

$$('div.hidden').invoke('show')

같은 기능을 하기 위해 첫번째 방법처럼 지나치게 많은 함수를 사용할 필요가 없다.

이벤트 핸들링[#9]

$$('div.collapsed').each(function(el){
  el.observe('click', expand);
})

추천하는 방법

$$('div.collapsed').invoke('observe', 'click', expand)

호출 체이닝[#10]

$$('input.date').invoke('observe', 'focus', onFocus);
$$('input.date').invoke('observe', 'blur', onBlur);

추천하는 방법

$$('input.date')
  .invoke('observe', 'focus', onFocus)
    .invoke('observe', 'blur', onBlur)

위 두가지 모두 같은 기능을 실행하게 되지만 앞의 예제처럼 $$() 함수를 두번이나 호출해서 처리할 필요가 없다. 아래의 경우처럼 체이닝(chaining nirvana)를 사용하면 된다.

테이블 형태의 html 내용변경하기[#11]

이전의 방법
$('productTable').innerHTML = 
  $('productTable').innerHTML + 
  '<tr><td>' + productId + ' '
  + productName + '</td></tr><tr><td>' 
  + productId + ' ' + productPrice + 
  '</td></tr>'

추천하는 방법

var rowTemplate = new Template('<tr><td>#{id} #{name}</td></tr><tr><td>#{id} #{price}</td></tr>');
$('productTable').insert(
  rowTemplate.evaluate({
    id: productId,
    name: productName,
    price: productPrice
  }))
)

위 두가지 모두 같은 기능을 실행하게 되지만 앞의 예제처럼 $$() 함수를 두번이나 호출해서 처리할 필요가 없다. 아래의 경우처럼 체이닝(chaining nirvana)를 사용하면 된다.

key 이벤트 감지하기[#12]

$('myInput').observe('keyup', function(e){
  if (e.keyCode == Event.KEY_TAB)
    doSomethingCoolWhenTabIsPressed();
})

keyCode는 KEY_RETURN, KEY_ESC, KEY_TAB, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN 과 같은 값들이 있다.

이벤트 가로채기[#13]

기본적인 방법 Event.observe('productInfo', 'click', displayProductInfo, false); // 'false' could be skipped
Event.observe('productInfo', 'click', displayProductInfo);

간단한 방법

$('productInfo').observe('click', displayProductInfo, false); // 'false' could be skipped
$('productInfo').observe('click', displayProductInfo);

insert() 메소드  사용하기[#14]

new Insertion.Bottom('blogEntry',
  new Template('<div><h2>#{name}</h2><p>#{content}</p></div>')
    .evaluate({
      name: blogEntry.name,
      content: blogEntry.content
    }));

// Insertion class is deprecated - it's recommended to use Element's insert method:

$('blogEntry').insert(new Template('<div><h2>#{name}</h2><p>#{content}</p></div>')
    .evaluate({
      name: blogEntry.name,
      content: blogEntry.content
    }), 'bottom' ); // "bottom" can be skipped

$('blogEntry').insert(new Template('<div><h2>#{name}</h2><p>#{content}</p></div>')
    .evaluate({
      name: blogEntry.name,
      content: blogEntry.content
    }));

위치값은 top, bottom, before, after 를  있다. 이 값을 생략한다면 디폴트는 bottom이다.

 다루기[#15]

다음은 .request를  일반적인 form이다.
$('register').observe('submit', function(e){
  Event.stop(e);
  $(this).request();
})

.getInputs 는 type과 name속성에 기초하여 요소를  쉬도록 해준다. 여기서는 "email" 이라는 이름의 요소를 직렬화하고 폼의 "action"  속성내 포함된 URI에 결과를 서브밋한다.

$('register').observe('submit', function(e){
  Event.stop(e);
  new Ajax.Request($(this).readAttribute('action'), {
    parameters: Form.serializeElements($(this).getInputs('', 'email'))
  })
})

앞서 본  대부분의 경우 유용하지만 일부 속성을 제외하고자 할때는 .reject를 사용한다.

$('register').observe('submit', function(e){
  Event.stop(e);
  new  {
    parameters: Form.serializeElements($(this).getElements()
      .reject(function(el){return el.hasAttribute('multiple')})
   );
  })
})