Skip to content
컴퓨터잡담
2010.03.27 12:51

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

조회 수 10299 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

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

단축키

Prev이전 문서

Next다음 문서

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

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')})
   );
  })
})
로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
637 Server php) 엑셀로 저장하기 2013.05.24 22066
636 Server php) 이미지 사이즈 구해서 0이면 게시물 내용 없애기 2013.07.05 11285
635 Server php.ini 파일설정으로 파일업로드 용량늘리기 2015.03.03 1152
634 HTMLPHPMSQL PHP5.4.4 form 변수 전달받기(get, post방식) 2015.07.22 8329
633 HTMLPHPMSQL PHP강좌 MySQL 연동 2014.11.11 5801
632 컴퓨터잡담 PHP로 FTP 접속 / 업로드 / 다운로드 등의 컨트롤 소스 2 3 2009.10.20 32766
631 컴퓨터잡담 PHP로 그림에 글자 입히기 2009.10.17 19996
630 컴퓨터잡담 php로 이미지를 mysql디비 저장하고 보여주는 소스 4 3 2009.10.17 62325
629 컴퓨터잡담 php에서 script로 변수 전달 후 html에 div로 내용 출력하기 1 3 2010.04.01 15903
628 프로세스 pinomate.exe 프로세스 삭제방법 6 2011.02.13 45999
627 컴퓨터잡담 postmassge 마우스 & PixelGetColor & 2009.12.22 7945
626 AutoHotKey PostMessage로 한글 사용하기 1 2 2011.02.09 16810
625 WindowsTip Process Explorer 불필요한 scvhost.exe 제거하기 2013.03.19 12131
» 컴퓨터잡담 Prototype.js를 제대로 사용하는 방법 2010.03.27 10299
623 Server Proxy and hide ip address problem 1 1 2013.04.03 11999
622 Server PuTTY Download Page(telnet,ftp,ssh) file 2016.12.06 5509
621 파이썬 python AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector' 해결방법 2023.05.07 47638
620 파이썬 python class def 2023.03.04 2368
619 파이썬 python html tag 제거 경로 금지 문자 제거 2021.10.26 3199
618 컴퓨터잡담 python pip 에러 line 193, line 197 해결방법 2021.08.12 4099
Board Pagination Prev 1 ... 13 14 15 16 17 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소