Category Archives: JAVASCRIPT

Prototype Javascript Framework – Object

이번엔 Object에 대해 알아보겠습니다. 대부분 객체의 타입을 알아보는 류의 메서드가 대거 포진해 있습니다.

Object의 하위 메서드들은 Prototype의 name space를 사용하여야 합니다. 이것은 곧 메서드를 사용할때 Object.로 시작해야 함을 뜻합니다. 일반적인 개발자들은 inspect()와 clone() 메서드를 많이 이용할 것입니다.

Object Methods —————————————————————————————————

clone : 객체를 얕은(shallow) 복사합니다. 기존의 객체가 가지고 있던 모든 프로퍼티를 복사합니다.
[code]Object.clone(obj) -> Object[/code]

예제)
[code]var o = { name: ‘Prototype’, version: 1.5, authors: [‘sam’, ‘contributors’] };
var o2 = Object.clone(o); o2.version = ‘1.5 weird’;


o2.authors.pop();


o.version
// -> 1.5
o2.version
// -> ‘1.5 weird’
o.authors
// -> [‘sam’]
// 얕은 복사가 되었음[/code]

extend : 소스 객체의 모든 프로퍼티를 복사합니다.
[code]Object.extend(dest, src) -> alteredDest[/code]
Prototype의 Javascript에서의 OOP 개발을 가능하게 하기 위한 메서드입니다. Object.extendClass.create 메서드등이 있습니다.

inspect : 디버깅을 위한 객체의 내용을 보여줍니다.
[code]Object.inspect(obj) -> String[/code]
객체의 값을 문자열로 보여줍니다. undefined와 null값을 구별하여 반환합니다.

예제)
[code]Object.inspect();
// -> ‘undefined’


Object.inspect(null);
// -> ‘null’


Object.inspect(false);
// -> ‘false’


Object.inspect([1, 2, 3]);
// -> ‘[1, 2, 3]’


Object.inspect(‘hello’);
// -> “‘hello'”[/code]

isArray : 객체가 배열인지 확인합니다.
[code]isArray(obj) -> Boolean[/code]

예제)
[code]Object.isArray([]);
//-> true


Object.isArray($w());
//-> true


Object.isArray({ });
//-> false[/code]

isElement : nodeType이 1인 엘리먼트인지 확인합니다.
[code]isElement(obj) -> Boolean[/code]

예제)
[code]Object.isElement(new Element(‘div’));
//-> true


Object.isElement(document.createElement(‘div’));
//-> true


Object.isElement($(‘id_of_an_exiting_element’));
//-> true


Object.isElement(document.createTextNode(‘foo’));
//-> false[/code]

isFunction : 객체가 함수(메서드)인지 확인합니다.
[code]isFunction(obj) -> Boolean[/code]

예제)
[code]Object.isFunction($);
//-> true


Object.isFunction(123);
//-> false[/code]

isHash : 객체가 Hash 클래스의 인스턴스인지 확인합니다.
[code]isHash(obj) -> Boolean[/code]

예제)
[code]Object.isHash(new Hash({ }));
//-> true


Object.isHash($H({ }));
//-> true


Object.isHash({ });
//-> false[/code]

isNumber : 객체가 소수점을 포함한 숫자형인지 확인합니다.
[code]isNumber(obj) -> Boolean[/code]

예제)
[code]Object.isNumber(0);
//-> true


Object.isNumber(1.2);
//-> true


Object.isNumber(“foo”);
//-> false[/code]

isString : 객체가 문자형인지 확인합니다.
[code]isString(obj) -> Boolean[/code]

예제)
[code]Object.isString(“foo”);
//-> true


Object.isString(“”);
//-> true


Object.isString(123);
//-> false[/code]

isUndefined : 객체가 undefined 인지 확인합니다.
[code]isUndefined(obj) -> Boolean[/code]

예제)
[code]Object.isUndefined();
//-> true


Object.isUndefined(undefined);
//-> true


Object.isUndefined(null);
//-> false


Object.isUndefined(0);
//-> false


Object.isUndefined(“”);
//-> false[/code]

keys : Hash타입의 객체의 전체 프로퍼티 네임을 가져옵니다.
[code]Object.keys(obj) -> [String…][/code]

예제)
[code]Object.keys();
// -> []


Object.keys({ name: ‘Prototype’, version: 1.5 }).sort();
// -> [‘name’, ‘version’][/code]

toHTML : 객체에 toHTML 메서드가 있으면 해당 메서드를 수행하고 없을 경우 String.interpret를 수행합니다.
[code]toHTML(obj) -> String[/code]

예제)
[code]var Bookmark = Class.create({
  initialize: function(name, url) {
    this.name = name;
    this.url = url;
  },
  toHTML: function() {
    return ‘<a href=”#{url}”>#{name}</a>’.interpolate(this);
  }
});


var api = new Bookmark(‘Prototype API’, ‘http://prototypejs.org/api’);


Object.toHTML(api);
//-> ‘<a href=”

toQueryString : URL인코딩이 된 query 문자열을 반환합니다.
[code]toQueryString(obj) -> String[/code]

예제)
[code]Object.toQueryString({ action: ‘ship’, order_id: 123, fees: [‘f1’, ‘f2’], ‘label’: ‘a demo’ })
// -> ‘action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'[/code]

value : Hash타입의 객체의 값들을 반환합니다.
[code]Object.values(obj) -> Array[/code]

예제)
[code]Object.values();
// -> []


Object.values({ name: ‘Prototype’, version: 1.5 }).sort();
// -> [1.5, ‘Prototype’][/code]

Prototype Javascript Framework – Form

그동안 빼먹고 있었군요. 중요도로 따지면 Element와 쌍벽을 이루는 Form에 대해서 알아보도록 합시다.
사실 웹페이지에 Form없이 이루어진 페이지를 찾기가 어려울 정도로 많이 쓰이고 있습니다. 데이터를 서버측으로 전송하기 위해서 사용할 수 있는 가장 기본적이면서 강력한 방법일테니깐요. 그 Form을 위해 만들어진 클래스에 대해 알아보겠습니다.

Form Methods —————————————————————————————————–
disable : 폼 혹은 폼 엘리먼트를 비활성화 합니다.
[code]disable(formElement) -> HTMLFormElement[/code]

예제)
[code]var form = $(‘disable-example’);
// form.disabled값에 따라 form.enable()과 form.disable()를 실행
form[form.disabled ? ‘enable’ : ‘disable’]();
form.disabled = !form.disabled;[/code]

enable : 폼 혹은 엘리먼트를 활성화 합니다.
[code]enable(formElement) -> HTMLFormElement[/code]
disable() 메서드로 비활성화 시킨 폼 및 폼 엘리먼트를 활성화 시킵니다.

findFirstElement : 숨겨지지 않고 비활성화되지 않은 첫번째 폼 컨트롤 엘리먼트를 반환합니다.
[code]findFirstElement(formElement) -> HTMLElement[/code]
이 메서드는 INPUT, SELECT, TEXTAREA 엘리먼트중에 첫번째 엘리먼트를 반환합니다. 문서상의 첫번째 엘리먼트로 반환하며 tabindex 순서는 따르지 않습니다. focusFirstElement() 메서드에서 사용합니다.

focusFirstElement : 숨겨지지 않고 비활성화되지 않은 첫번째 폼 컨트롤을 Activate 합니다.
[code]focusFirstElement(formElement) -> HTMLFormElement[/code]
findFirstElement를 사용하여 첫번째 엘리먼트를 찾아온 후 activate() 메서드를 호출합니다.

getElements : 폼의 모든 폼 컨트롤 엘리먼트를 배열로 반환합니다.
[code]getElements(formElement) -> array[/code]
주의!! SELECT컨트롤의 경우 하위 OPTION 컨트롤은 결과에 포함되지 않습니다.

getInputs : 폼의 모든 INPUT 폼 컨트롤 엘리먼트를 반환합니다.
[code]getInputs(formElement [, type [, name]]) -> array[/code]
폼의 모든 INPUT폼 컨트롤 엘리먼트를 가져옵니다. type과 name을 옵션으로 줄 수 있습니다.

예제)
[code]var form = $(‘myform’);


form.getInputs();
// -> 모든 INPUT 폼컨트롤 엘리먼트


form.getInputs(‘text’);
// -> INPUT 폼컨트롤 엘리먼트중에 type이 text인 엘리먼트


var buttons = form.getInputs(‘radio’, ‘education’);
// -> type이 radio이며 name이 education인 폼컨트롤 엘리먼트를 disable()
buttons.invoke(‘disable’);[/code]

request : form의 action 파라미터값으로 submit을 합니다.
[code]request([options]) -> new Ajax.Request[/code]
이 메서드야 말로 페이지 이동 없이 form submitting을 하게 만들어 주는 주체가 되는 메서드인것 같습니다. 폼 안의 폼 컨트롤들의 값을 모아 form의 action 파라미터에 있는 페이지로 Request를 요청합니다. 이후 결과 처리도 할 수 있습니다.



  • form에서 method 파라미터를 가지고 있다면 Ajax.Request의 method 파라미터로 전달됩니다.

  • method가 없을 경우에는 기본적으로 POST로 설정됩니다.

  • ‘키-값’의 쌍을 이루는 폼 컨트롤들의 값은 parameters 옵션에 전달됩니다.

예제)
[code]<form id=”person-example” method=”POST” action=”/user/info”>
  <fieldset><legend>User info</legend>
    <div><label for=”username”>Username:</label>
    <input type=”text” name=”username” id=”username” value=”” /></div>
    <div><label for=”age”>Age:</label>
    <input type=”text” name=”age” id=”age” value=”” size=”3″ /></div>
    <div><label for=”hobbies”>Your hobbies are:</label>
    <select name=”hobbies[]” id=”hobbies” multiple=”multiple”>
      <option>coding</option>
      <option>swimming</option>
      <option>hiking</option>
      <option>drawing</option>
    </select>
  </div>
  <div class=”buttonrow”><input type=”submit” value=”serialize!” /></div>
  </fieldset>
</form>[/code]
[code]$(‘person-example’).request();
// Request 완료~!


// 다음과 같은 방법으로 콜백함수를 사용할 수 있습니다.
$(‘person-example’).request({
  onComplete: function(){ alert(‘Form data saved!’) }
})[/code]
다른 파라미터 값을 추가적으로 사용하고 싶을경우에는 parameters인자를 사용하면 됩니다. 마찬가지로 method도 임의로 변경 할 수 있습니다.
[code]$(‘person-example’).request({
  method: ‘get’,
  parameters: { interests:’JavaScript’, ‘hobbies[]’:[‘programming’, ‘music’] },
  onComplete: function(){ alert(‘Form data saved!’) }
})[/code]

reset : 폼의 내용을 디폴트 값으로 초기화 합니다.
[code]reset(formElement) -> HTMLFormElement[/code]

예제)
[code]Form.reset(‘contact’);
// 다음과 동일


$(‘contact’).reset();
// 둘다 reset 버튼을 누른것과 동일한 효과를 가져옴[/code]

serialize : Ajax Request에 최적화된 문자열로 변환하거나 혹은 해시형 객체로 반환합니다.
[code]serialize(formElement[, getHash = false]) -> String | object[/code]

예제)
[code]$(‘person-example’).serialize();
// -> ‘username=sulien&age=22&hobbies=coding&hobbies=hiking’
$(‘person-example’).serialize(true);
// -> {username: ‘sulien’, age: ’22’, hobbies: [‘coding’, ‘hiking’]}[/code]

serializeElements : Form.serialize와 동일하나 특정 엘리먼트 배열을 인자로 받습니다.
[code]serializeElements(elements[, getHash = false]) -> string[/code]

예제)
[code]Form.serializeElements( $(‘myform’).getInputs(‘text’) )
// -> serialized data[/code]

Form.Element Methods ——————————————————————————————-
이 클래스는 폼 관련 메서드중에서도 폼안의 컨트롤 엘리먼트를 위한 메서드들을 모아놓은 클래스입니다.
Form과 많은 부분이 중복되니 새로운것만 써보도록 하겠습니다.

activate : 엘리먼트의 컨텐츠 영역에 커서가 이동하며 내용이 있었다면 해당 내용이 선택됩니다.
[code]activate(element) -> HTMLElement[/code]

예제)
[code]Form.Element.focus(‘myelement’).select();
$(‘myelement’).activate();[/code]

clear : text INPUT의 내용을 삭제합니다.
[code]clear(element) -> HTMLElement[/code]

예제)
[code]$(‘some_field’).onfocus = function() {
  // 이미 삭제되었다면 아무것도 하지 않음
  if(this._cleared) return
  // this키워드는 폼컨트롤 엘리먼트 자신을 지칭
  this.clear()
  this._cleared = true
} [/code]

disable : Form 클래스와 동일

enable : Form 클래스와 동일

focus : 해당 엘리먼트에 키보드 포커스를 줍니다.
[code]focus(element) -> HTMLElement[/code]

예제)
[code]Form.Element.focus(‘searchbox’);
// 위와 거의 동일. 하지만 아래는 JS native 메서드이기 때문에 엘리먼트를 반환하지 않음
$(‘searchbox’).focus();[/code]

getValue : 엘리먼트의 값을 가져옵니다. 간단하게 사용할 수 있는 유틸리티 함수인 $F()가 있습니다.
[code]getValue(element) -> string | array[/code]

예제)
[code]var form = $(‘contact’);
var input = form[‘company’];
Form.Element.getValue(input);


// 다음과 같은 방법도 있음
$(input).getValue();
// $()메서드는 확장된 엘리먼트를 가져올 수 있음
// 하지만 $F(input)을 사용하면 위의 과정을 더욱 단축 시킬 수 있음[/code]

present : 엘리먼트안의 값이 존재하는지를 확인합니다.
[code]present(element) -> boolean[/code]

예제)
[code]$(‘example’).onsubmit = function(){
  var valid, msg = $(‘msg’)
  // 두 필드의 prestion() 결과가 참인가?
  valid = $(this.username).present() && $(this.email).present()
  if (valid) {
    // 기본적인 처리를 한 후 return true 한다
    msg.update(‘Passed validation!’).style.color = ‘green’
  } else {
    msg.update(‘Please fill out all the fields.’).style.color = ‘red’
  }
  return false
}[/code]

select : 해당 폼컨트롤의 값 전체를 선택합니다.
[code]select(element) -> HTMLElement[/code]

예제)
[code]$(‘searchbox’).onfocus = function() {
  Form.Element.select(this);
  // 다음의 native 메서드를 사용할 수 있음. 하지만 엘리먼트를 반환하지 않음
  this.select();
}[/code]

serialize : Form 클래스와 동일