이 내용 역시 kangax씨가 작성한 것으로, Prototype 코드를 효율적으로 리팩토링한 예제입니다. 사실, 리팩토링이라기 보다는 Prototype의 유틸리티 함수의 활용법을 알리려는 것 처럼 보이네요.
반복 1
// before
function hideall() {
hidediv('dropdown1');
hidediv('dropdown2');
hidediv('dropdown3');
hidediv('dropdown4');
hidediv('dropdown5');
hidediv('dropdown6');
hidediv('dropdown7');
}
// after
$R(1, 7).each(function(n) {
hidediv('dropdown' + n);
})
반복 2
// before
function resetnotes() {
$('left1').removeClassName('learn');
$('left1').removeClassName('play');
$('left1').removeClassName('grow');
$('left1').removeClassName('join');
}
// after
// storing element's reference for faster access
var left1 = $('left1');
// creating array of strings and iterating over them
$w('learn play grow join').each(function(s){
left1.removeClassName(s);
})
// another solution
Element.addMethods({
removeClassName: Element.Methods.removeClassName.wrap(function() {
var args = $A(arguments), proceed = args.shift(), element = $(args.shift());
if (args.length > 1) {
// this is our modified behavior (only if more than 1 argument was passed)
element.className = element.className.replace(new RegExp("\s*(" + args.join('|') + ")\s*"), '');
return element;
}
// and this is a default one
return element.proceed();
})
})
삼항 연산
// before
if (typeof this.prevbutton == 'object') {
$(prevmonth).appendChild(this.prevbutton);
} else {
$(prevmonth).update(this.prevbutton);
}
// after
$(prevmonth)[typeof(this.prevbutton) == 'object' ? 'appendChild' : 'update'](this.prevbutton);
체인
// before
$(nextmonth).addClassName('calcontrol');
$(nextmonth).addClassName('calnextmonth');
$(nextmonth).observe('click',this.nextmonth);
// after
$(nextmonth).addClassName('calcontrol calnextmonth').observe('click', this.nextmonth);
요런 코드들은 눈에 자주 밟혀야 써먹습니다. ^^;
Comments
Got something to add? You can just leave a comment.
Your Reaction Time!