이제 프로젝트에서도 prototype.js를 js의 프레임웍으로 사용하는 경우도 많고
개인적으로도 관심을 많이 가지고 계신것 같은데 관련 글이 있어서 올립니다.
How well do you know prototype
//바르지 못한 방법:
document.getElementById("foo ")
//적당한 방법: 놀랍게도 어떤 사람들은 이것에 대해 잘 모른다.
$("foo ")
//바르지 못한 방법:
var woot = document.getElementById("bar").value
var woot = $("bar").value
//적당한 방법: 폼 값의 편리하고 빠른 호출
var woot = $F("bar")
//바르지 못한 방법:
$('footer').style.height = '100px';
$('footer').style.background = '#ffc';
//적당한 방법: 모든 브라우저가 W3C의 권고를 따르고 있지 않다.
$('footer').setStyle({
height: '100px',
background: '#ffc'
})
//바르지 못한 방법:
$('coolestWidgetEver').innerHTML = 'some nifty content'
//적당한 방법:
$('coolestWidgetEver').update('some nifty content')
// 아래와 같은 문법 구사가 가능해 지므로
$('coolestWidgetEver').update('some nifty content').addClassName('highlight').next().hide()
//바르지 못한 방법:
new Ajax.Request('ninja.php?weapon1=foo&weapon2=bar')
//적당한 방법: 보기 좋으며 보다 나은 파라메터 구조 사용
new Ajax.Request('ninja.php', {
parameters: {
weapon1: 'foo',
weapon2: 'bar'
}
})
//바르지 못한 방법:
new Ajax.Request('blah.php', {
method: 'POST',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
encoding: 'UTF-8',
})
//적당한 방법: 기본옵션은 생략하라!
new Ajax.Request('blah.php')
//바르지 못한 방법:
Event.observe('myContainer', 'click', doSomeMagic)
//적당한 방법: 논쟁의 여지가 있지만 객체지향적이다!
$('myContainer').observe('click', doSomeMagic)
//바르지 못한 방법:
$$('div.hidden').each(function(el){
el.show();
})
//적당한 방법: 슬프게도 이 사용법을 아는 사람들이 많지 않다는 사실.
$$('div.hidden').invoke('show')
//바르지 못한 방법:
$$('div.collapsed').each(function(el){
el.observe('click', expand);
})
//적당한 방법: invoke를 이용한 이벤트 핸들링, 졸라 쉽다!
$$('div.collapsed').invoke('observe', 'click', expand)
//바르지 못한 방법:
$$('input.date').invoke('observe', 'focus', onFocus);
$$('input.date').invoke('observe', 'blur', onBlur);
//적당한 방법: $$는 오버해드가 크기 때문에 invoke를 사용하면 $$를 여러번 사용할 필요도 없다.
$$('input.date').invoke('observe', 'focus', onFocus).invoke('observe', 'blur', onBlur)
//바르지 못한 방법:
$('productTable').innerHTML =
$('productTable').innerHTML +
'<tr><td>' + productId + ' '
+ productName + '</td></tr><tr><td>'
+ productId + ' ' + productPrice +
'</td></tr>'
//적당한 방법: Template 클래스는 정말 쓸만한 DOM 솔루션이다. 하지만 잘 사용되고 있지 않는 것 같다.
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
}))
)
1) Detecting key events easily
How do we detect which key was pressed? Prototype provides set ofkey event aliases so that we don’t have to remember that return is “13″and escape is “27″. Almost all major keys are aliased: KEY_RETURN,KEY_ESC, KEY_TAB, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN. See full list in API docs
$('myInput').observe('keyup', function(e){
if (e.keyCode == Event.KEY_TAB)
doSomethingCoolWhenTabIsPressed();
})
2) You won’t need event capturing (most likely)
Sometimes I see capturing phase being explicitly set to false inEvent’s observe method. The good thing is that it’s set to false bydefault and you would rarely need to use it. The following 2 lines arefully identical so we can just skip this last argument:
Event.observe('productInfo', 'click', displayProductInfo, false); // 'false' could be skipped
Event.observe('productInfo', 'click', displayProductInfo);
or a short way:
$('productInfo').observe('click', displayProductInfo, false); // 'false' could be skipped
$('productInfo').observe('click', displayProductInfo);
3) insert() wisely
Another one of those “it’s-there-by-default” values is a positionargument of Element’s insert method. Surprisingly it’s not mentionedanywhere in the docs - I accidentally found it wondering through thesource one day. insert accepts one of four position values: top, bottom, before, and after. If we omit this argument, it defaults to bottom (and luckily this happens to be the most common case). The following lines behave identically:
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
}));
4) Forms gone wild
Plain form submission is quite easy but what if we want to preventcertain elements from being serialized before submitting form via ajax?Let’s take a look at few ways to do this:
Plain form submission using .request
$('register').observe('submit', function(e){
Event.stop(e);
$(this).request();
})
Using .getInputs makes it easy to filter out elements based on typeand name attributes. In this example we’re serializing elements withname ‘email’ and submitting result to the URI contained in form’s“action” attribute
$('register').observe('submit', function(e){
Event.stop(e);
new Ajax.Request($(this).readAttribute('action'), {
parameters: Form.serializeElements($(this).getInputs('', 'email'))
})
})
Using .getInputs could help most of the time but what if we want toexclude elements that have “multiple” attribute? We might try somethinglike this:
$('register').observe('submit', function(e){
Event.stop(e);
new Ajax.Request(this.readAttribute('action'), {
parameters: Form.serializeElements($(this).getElements()
.reject(function(el){return el.hasAttribute('multiple')})
);
})
})
Wow, what’s going on over here?!
When submit event occurs, we prevent default submit action Event.stop(e), get all form’s elements this.getElements(), iterate over them REJECTING those that have “multiple” attribute .reject(function(el){return el.hasAttribute('multiple')}). The filtered collection is then serialized Form.serializeElements() and is submitted via ajax new Ajax.Request()
This is all very cool but here’s the reason why learning CSS3selectors might be a good thing (the results from both - reject-basedand selector-based filtering are the same):
$('register').observe('submit', function(e){
Event.stop(e);
new Ajax.Request($(this).readAttribute('action'), {
parameters: Form.serializeElements($$('#register input:not([multiple])'))
})
})
'프로그래밍 > javascript' 카테고리의 다른 글
| createElement로 select 생성후 onChange이벤트 주기 (0) | 2008.12.22 |
|---|---|
| 자바스크립트 Explorer debugger (0) | 2008.12.22 |
| [javascript : merge] (0) | 2008.12.09 |
| 셀렉트박스 선택된 값과 텍스트 가져오기. (0) | 2008.12.05 |
| prototype.js를 위한 개발자 노트 1.5.0버전을 다룸 (0) | 2008.09.09 |

