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

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

조회 수 10302 추천 수 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
번호 분류 제목 날짜 조회 수
837 파이썬 파이썬 pyautogui 화면에 여러개의 동일한 이미지가 있을 때 n번째 이미지 선택하기 2023.02.12 5164
836 파이썬 파이썬 pyautogui 자주쓰는 이미지 서치 def 지정하기 2023.02.12 5321
835 컴퓨터잡담 파이썬 pyautogui 명령어 2021.06.06 1564
834 파이썬 파이썬 openyxl 엑셀파일(xlsx) 저장하기 2021.09.11 2664
833 파이썬 파이썬 ModuleNotFoundError: No module named 'pip' 갑자기 나타난 오류! 2022.02.13 4139
832 컴퓨터잡담 파이썬 JSON으로 받아온 데이터의 Key 값 가져오기 2021.08.27 11105
831 컴퓨터잡담 파이썬 IF문 2021.06.16 5319
830 컴퓨터잡담 파이썬 gspread 사용법 file 2021.06.25 11682
829 파이썬 파이썬 googleapiclient 모듈이 설치가 안될때 해결방법 1 2022.03.27 9950
828 컴퓨터잡담 파이썬 FTP 업로드/다운로드 하기 2021.07.31 3414
827 컴퓨터잡담 파이썬 for문으로 자동변수 생성하기 2021.06.24 3811
826 컴퓨터잡담 파이썬 find, select 사용법 2021.07.30 1448
825 파이썬 파이썬 easyocr 이미지 문자 인식 2023.01.16 10449
824 파이썬 파이썬 dictionary 딕셔너리 조작 2021.09.13 2605
823 파이썬 파이썬 datetime 모듈로 초간단 날짜 표현하기 2021.09.11 2750
822 컴퓨터잡담 파이썬 Beautifulsoup 웹크롤링 차단시 해결방법 2021.07.23 1525
821 컴퓨터잡담 파이썬 Beautifulsoup html의 특정 주소만 가져오기 file 2021.06.14 3001
820 파이썬 파이썬 any, all 사용하기(배열데이터 안에 값이 하나라도 있는지 또는 모두 있는지 비교) 2021.09.11 1996
819 컴퓨터잡담 티맥스OS 무료배포도 판매 수익의 세배이상 가능하다 2 2009.07.26 24576
818 컴퓨터잡담 티맥스 윈도우가 살아남는 방법 5 1 2009.07.24 22707
Board Pagination Prev 1 ... 3 4 5 6 7 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소