요즘 prototype에서 자주 사용할만것들을 짤라서 모으고 있는데  Event.unloadCache()라는걸 확인했다.

처음볼땐 그냥 아무것도 아니구나 하고 넘어갔는데 이번에 이벤트를 추가하는것을 만들려고 확인중 엄청난 일을 하는것을 알게됬다.

알고 보니 ie에서 attachEvent을 사용할때 unload시 detachEvent을 안해주면 가비지컬랙션이
회수를안하고 그냥 브라우져에 상주해서 그것을 가비지 컬랙션이 회수할수 있게끔하는 역활을 하는것이였다.(관련글)-물론 브라우져를 닫으면 상관없음.
(JQuery는 귀찮은지 고전적인 방법으로 매소드 추가)

가끔 여기저기에 있는 자바스크립트소스를 확인해보는데 특정프래임워크를 사용하지 않는곳은
거의 unloadCache와 같은 기능을 해주는곳이 없다.

이벤트를 추가하는것은 common method라 굉장히 많이 쓰이는데도 안하는거 보면 별차이가 없나?..:(

아..나만 몰랐나..ㅡㅡ;

참고글
dean.edwards의 add-event
Understanding and Solving Internet Explorer Leak Patterns
addEvent() considered harmful

Posted by 전용우
,
Posted by 전용우
,

Dom 사용하기.

프로그래밍 2007. 4. 21. 07:12
Chris Heilmann라는 사람의 Dom Scripting강의 약 10분정도로 dom에 대해
설명함. 일단 중요한건 쉬움.:)

Beginning JavaScript with DOM Scripting and Ajax이란 책을 쓴 저자.
해당블로그에 많은 내용이 있으니 한번 방문해보세요.

Posted by 전용우
,

파이어폭스에선 위에 두가지 이벤트를 제공한다.

첫번째 capturing 이벤트는 이벤트가 상위 노드부터 시작하여
하위노드로 내려가는 형식이다.

capturing


두번째 방식은 bubbling방식 이방법은 위에 capturing방식과 반대로
실행이 되는노드를 시작으로 상위노드로 올라가며 이벤트를 발생한다.

bubbling

이렇게 두가지의 이벤트가 있으며

 

document.getElementById("아이디").”이벤트” = “함수”;


위와 같이 일반적인 방식은 bubbling방식으로 작동한다.
그리고 capturing방식은 ie에선 작동을 하지 않는다.


만약 prototype.js에서 capturing방식을 사용하고 싶을때는
Event.observe(element, eventName, handler[, useCapture = false]);

위에 useCapture부분을 true로 바꾸어서 등록하면된다.

그리고 scriptaculous에서 drag&drop구현시 한노드가 여러 Droppables에 등록되어있고
해당 Droppables의 zone이 겹쳐있으면 하위 Droppables의 이벤트만 실행된다. 이점을
이용하면 보다 편리하게 장바구니를 구현할수 있다.물론 레이어가 겹쳐있어도 그중에 하나가  Droppables zone이면 Droppables의 이벤트는 실행된다.

혹,capturing 이나 bubbling을 하기 싫다면 ie에선 window.event.cancelBubble = true;
그이외는 event.stopPropagation() 으로 막을수 있다.

참고글:DOM Design Tricks II
Posted by 전용우
,

Dom Scripting

프로그래밍 2007. 2. 7. 02:41

Dom Scripting Book Image
Dom Scripting

이책은 일단 쉽고,빠르게 읽을수 있고,유용하며 재미있다.
조금이라도 javascript을 알고있다면 너무 쉽게 읽을수 있다.
(시간이 없다면 3~10장까지만 보면됨.)


이책에 내용을 요약하자면.

  • Graceful degradation
    (만약에 자바스크립트를 잘 사용하고 있다면 자바스크립트가 없어도 사용자는
    네비게이션을 할수 있다.)
  • Unobtrusive JavaScript
    (자바스크립트는 부과적인 기능을 하는것이다.)
  • Backwards compatibility
    (뒤떨어진 환경에서도 가능해야한다.)

물론 위의글은 모두 정답이다.당연하고 기초적이긴 하지만 지키기에는 많은 노력이 뒤받침이되야한다.지금껏 해왔던 습관들을 버려야하고 기타 개발여건도 받쳐줘야하고..

내생각은 처음부터 하면 좋지만 여건이 안되면 나중에라도 서버단만 리팩토링을 하는것이 아니라 프론트도 리팩토링을 하면서 바꾸면 될것 같다.
 



 

  1. var value = element.attribute=value;
    var value = element.getAttribute(attribute); 같음. [본문으로]
  2. element.attribute=value;
    element.setAttribute(attribute)=value; 같음. [본문으로]
  3. node.childNodes[0];
    node.firstChild; 같음. [본문으로]
  4. node.childNodes[node.childNodes.length-1];
    node.lastChild; 같음. [본문으로]
  5. previousSibling은 반대. [본문으로]
Posted by 전용우
,
<textarea cols="50" rows="3" onclick="javascript:select();">

Highlight this text

</textarea>


별다른 코딩없이 코드를 복사하기 위해서 하이라이트 기능주기.
input box등에도 사용가능.

예제:


원글:Click to Hightlight all text: It’s Easier than you think.
Posted by 전용우
,

Scope in Javascript

프로그래밍 2006. 12. 20. 15:21

요즘 prototype을 뜯어 보구 있는데 생각보다 벽[각주:1]이 높다..ㅡㅡ;

내가 제일 헤갈린것이 this의 scope였다.
모든 this가 같은 this인줄만 알았는데..완전 잘못알았다.
그래서 구글링을 하던중 아주 좋은 아티클을 본 덕분에 어느정도 감을 잡았다.

그래도 나는 나의 기억력을 알고 있기때문에 위의 아티클을 중심으로
일단 정리를 하도록 한다..ㅡㅡ;

이 아티클에서는 4개의 정도의 this를 설명하고 몇개는 this의 scope의 대한 얘기를 한다.

1.Calling an Object’s Method

<script type="text/javascript">                                             
  var deep_thought = {
   the_answer: 42,
    ask_question: function () {
      return this.the_answer;
    }
  };
 
  var the_meaning = deep_thought.ask_question();
</script>

즉,Object에서 method를 호출할때의 this는 호출한 본인을 뜻한다.
간단히 말하면 호출한 함수의 "."앞에의 Object를 의미한다.
위에서 the_meaning은 42가 나타난다.


2.Constructor

  function BigComputer(answer) {
    this.the_answer = answer;
    this.ask_question = function () {
       return this.the_answer;
    }
  }
 
  var deep_thought = new BigComputer(42);
  var the_meaning = deep_thought.ask_question();

new 키워드를 가지고 생성자를 사용하는 함수인경우의  this의 의미는 새로 생긴
object를 말한다.
위의 예를 들면 BigComputer의 바로 밑에 있는 this는 this.the_answer,this.ask_question들은 deep_thought을 지칭한다.[각주:2]
하지만 this.ask_question안의 this.the_answer는 좀 다른 의미를 가지고 있다.[각주:3]
2차 this는 다른 변수와 달리 scope chain[각주:4]에서 읽어 오는것이 아니라 단순히 deep_thought에서 읽어온다.
즉,2차 this는 현재 기본 context를 참고한다.
위의 같은경우는 하나의 context이기 때문에 상관없지만  아래의 예인 Complications의 경우는 context가 여러개여서 틀려진다.


3.Function Call

  function test_this() {
    return this;
  }
  var i_wonder_what_this_is = test_this();

이번경우는 아무것도 없이 this를 리턴하게 되면 window object가 반환된다.


4.Event Handler


이벤트 핸들러에서의 this는 종류가 두가지 이다.

첫번째로는 아래와 같이 이벤트 핸들러를 인라인으로 사용했을경우

  function click_handler() {
    alert(this); // alerts the window object
  }

...
<button id='thebutton' onclick='click_handler()'>Click me!</button>

이렇게 한다면 click_handler의 this는 생각했던 dom이 아니라 window object가 된다.


2번째 방법은 javascript에서 이벤트 핸들러를 정의한경우.

  function click_handler() {
    alert(this); // alerts the button DOM node
  }
 
  function addhandler() {
    document.getElementById('thebutton').onclick = click_handler;
  }
 
  window.onload = addhandler;
...
<button id='thebutton'>Click me!</button>

위와 같이 정의 한다면 click_handler의 this는 button의 dom객체가 된다.


5.Complications

function BigComputer(answer) {
  this.the_answer = answer;
  this.ask_question = function () {
  alert(this.the_answer);
  }
}
 
function addhandler() {
  var deep_thought = new BigComputer(42),
  the_button = document.getElementById('thebutton');

  the_button.onclick = deep_thought.ask_question;
}
 
window.onload = addhandler;

위는 좀 복잡하지만 자주쓰는 부분이므로 알아보자.
위의 예는 thebutton의 엘리먼트의 onclick이벤트에 addhandler를 추가하는 내용이다.
언뜻보기에는 큰문제가 없다.

예상대로라면 당연히 thebutton을 클릭할경우 '42'가 호출할것을 예상한다.
하지만 undefined가 나온다.위의 내용을 이해했다면[각주:5] 쉽게 알수 있을것이다.
이유는 현재 이벤트 핸들러의 context안에 BigComputer의 context가 있다.
그렇기 때문에 1차this는 scope chain에 의해서 deep_thought을 나타내고 2차this는 현재 기본context인 이벤트핸들러를 지칭한다.그래서
이벤트 핸들러의 the_answer를 찾게된다.하지만 없기 때문에 undefined가 나오는것이다.
(setTimeout의 함수롤 비슷한 행동을 가지고 있다.)


6.Manipulating Context With .apply() and .call()

그럼 위와 같이 event 나 setTimeout을 동작할때 native context[각주:6]
일단은 해결할수있는 메소드가 2개있다[각주:7]
이메소드는 this를 명확히 지칭해주므로 context을 고정할수 있다.

일단 간단한 예로 call,apply의 사용법을 알아보자.

var first_object = {
  num: 42
};
var second_object = {
  num: 24
};
 
function multiply(mult) {
  return this.num * mult;
}
 
multiply.call(first_object, 5); // returns 42 * 5
multiply.call(second_object, 5); // returns 24 * 5
......
multiply.apply(first_object, [5]); // returns 42 * 5
multiply.apply(second_object, [5]); // returns 24 * 5

먼저 call을 보면 의미는 multiply를 호출하는데 this의 대상은 first_object이고 파라메터는 5이다.[각주:8]
그렇기 때문에 그냥 multiply(5)를 하면 this.num 이 없어서 오류가 나지만 this를 first_object로 정했기 때문에 에러가 나지 않는다.
두분째의 apply는 call과 모드 같은 말이지만 파라메터에 차이가 있다.apply의 두번째인자는 해당함수의 파라메터를 뜻하는데 배열형태를 이룬다.
즉,파라메터가 유동적으로 변하거나 할때에 유용히 사용된다.

그럼  call을 가지고 아까의 문제를 해결해보자.

function addhandler() {
  var deep_thought = new BigComputer(42),
  the_button = document.getElementById('thebutton');
 
  the_button.onclick = deep_thought.ask_question.call(deep_thought);
}
위와 같이 call을 할때 this를 대신할 object를 넘겨주므로서 2차 this는 deep_thought을 참조하게 되고 정상적으로 출력이 된다.


7.The Beauty of .bind()

이와 같은 문제점을 해소하기 위해서 Prototype JavaScript framework 에서는
편리한 방법으로 아래와 같은 멋진 메소드를 제공한다.[각주:9]
Function.prototype.bind = function(obj) {
  var method = this,
  temp = function() {
    return method.apply(obj, arguments);
  };
 
  return temp;
}

multiply.call(first_object, 5); 이렇게 표현했던 방식이 multiply.bind(first_object); 으로 바뀐다.

원문:Scope in JavaScript

요즘 prototype.js을 공부하고 있는데 생각보다 어렵다.
할건 너무 많은데..생각만큼 속도가 안나네..

  1. 그누가 자바스트립트가 쉬운 언어라고 했던가... [본문으로]
  2. 해당this는 1차 this로 표현 [본문으로]
  3. 해당this는 2차 this로 표현 [본문으로]
  4. 참고:scope chain [본문으로]
  5. 결코 이해했을거란 생각을 안한다.내가 생각해도 글을 잘못쓰는것 같다.ㅡㅡ; 이해가 잘안된다면 원문을 읽기를 추천합니다. [본문으로]
  6. 자신의 context,위에서 보면 이벤트가 아닌 BigComputer의 context을 말함. [본문으로]
  7. 이것 이외에도 this 바꿔치기가 있습니다. [본문으로]
  8. 다 알고있겠지만 저같은 초보자분들을 위해.. [본문으로]
  9. bind 이외에도 bindAsEventListener가 있음. [본문으로]
Posted by 전용우
,

javascript를 사용하다보면 exception을 handing하고 싶은경우가 있다.
에러가 나면 ie에서 노랗게 경고메세지를 알리는경우가 있는데 그렇게하면 알기가 힘들다.
물론 각종 툴을 사용하면 알수가 있으나 그렇게 하는것보다 exception을 handing하면
좀더 효율적으로 작업을 할수가 있을것 같았는데 전혀 방법도 몰라 할수없었다.
이번기회에 exception을 공부할기회가 있어서 정리 하도록한다. ㅡㅡ;

javascript 역시 다른 언어 같이 exception이 있다.
그리고 try,catch,finally,thorw 역시 존재한다.

그래서 간단히 exception의 사용법을 알아 보도록하자.
기본적은 구문은 다른 언어와 같이..

try{
.........
}catch(e){
.........(throw expression;)
}finally{
.........
}

이런식으로 사용된다.
물론 알겠지만 간단히 설명하면
try구문에서 exception이 일어나면 catch문으로 exeption을 처리할수도 있고
throw을 던져 처리할수도 있다.
마지막으로 finally을 실행한다.
(finally는 자원의리소스 반납등을 할때 사용된다.
이부분은 잘사용하게 되면 메모리 릭현상을 방지할수 있다.)
일반적은 언어와 크게 차이 없음.


그리고 exception에는 javascript 1.5기준으로 하여 아래 6가지가 있다.

EvalError - 잘못된 방법으로 eval()을 사용했을때.
RangeError - 허락되는 숫자범위를 넘쳤을때.
ReferenceError - 허용되지 않는 참조를 사용했을때.
SyntaxError - 자바스크립트 파싱중 syntax에러 났을때.
TypeError - 사용할수 없는 변수를 썼을때.
URIError - encodeURI() 나 decodeURI()을 잘못된 방법으로 썻을때.

이 exception들은 name,message라는 2가지 프로퍼티를 갖고 있는데.
당연히도 name은 exception의 이름,message는 exception의 message를 말한다.

그리고 instanceof을 사용하여 exception을 구별해 사용하기도 한다.


만약에 사용자정의 exception을 가지고 만들고 싶다면.

function UserException (message) {
  this.message=message;
  this.name="UserException";
}
myUserException=new UserException("Value too high");
throw myUserException;

이런식으로 자신의 exception을 만들어서 사용할수도 있다.
(물론 이름은 맘대로 정해도 상관없음.)


요즘 갈수록 javascript의 사용이 늘고 거대화지면서 서버코드를 할때와 같이
exeption과 logging전략이 필요한것 같다.


참고한곳:
Core JavaScript 1.5 Guide:Exception Handling Statements:try...catch Statement
JavaScript Exception Handling
Posted by 전용우
,


1.변수는 블록레벨 범위가 없다.


2.기본형과 참조형


3.프로퍼티 정의방법.


4.Prototype 과 상속
5.인스턴스변수(메소드)와 클래스변수(메소드)

6.함수
7.super class 와 sub class
8.Garbage collection
9.Exception
10.Scope
Posted by 전용우
,

Tool
aptana:http://www.aptana.com/(강추-이클립스기반)
jsecilpse:http://www.interaktonline.com/Products/Eclipse/JSEclipse/Try-Download/
             (이클립스플러그인-위에꺼가 더좋은것 같음)
GTW : http://code.google.com/webtoolkit/

Javascript Library
Jquery : http://jquery.com/demo/thickbox/
moo.fx : http://www.moofx.mad4milk.net/
dojo toolkit : http://www.dojotoolkit.org/
mochikit : http://www.mochikit.com/about.html
JSPON(JavaScript Persistent Object Notation) : http://www.jspon.org/
qooxdoo : http://qooxdoo.org/
JavascriptLint : http://www.javascriptlint.com/
Yahoo! JavaScript Developer Center : http://developer.yahoo.com/javascript/
Prototype : http://prototype.conio.net/
script.aculo.us : http://script.aculo.us/
javascript manual :http://koxo.com/lang/js/
ajaxpattern : http://ajaxpatterns.org/
dom manual: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference
                  http://developer.mozilla.org/ko/docs/Gecko_DOM_Reference

Javascript Articles
Script.aculo.us Behaviour Driven Development Testing :
http://ajaxian.com/archives/scriptaculous-behaviour-driven-development-testing

New in JavaScript 1.7 :
http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7
The Decorator Pattern for JavaScript :
http://beppu.lbox.org/articles/2006/08/22/the-decorator-pattern-for-javascript
SmoothMovingLayer:
http://hyeonseok.com/pmwiki/index.php/Javascript/SmoothMovingLayer
Transparent Messages in JavaScript:
http://ajaxian.com/archives/transparent-messages-in-javascript
http://firejune.com/index.php?pl=971
A flexible slideshow:
http://www.madb.net/slideshow/
http://smoothslideshow.jondesign.net/index.html
Lessons in JavaScript Performance Optimization:
http://ajaxian.com/archives/lessons-in-javascript-performance-optimization
bytefx: simple effects:
http://ajaxian.com/archives/bytefx-simple-effects
Upgraded jQuery Spy:
http://leftlogic.com/info/articles/jquery_spy2
Dynamic Graphics in the Browser:
http://ajaxian.com/archives/dynamic-graphics-in-the-browser
Yahoo! Browser-Based Authentication:
http://ajaxian.com/archives/yahoo-browser-based-authentication
Fresh Logic Studios Scripts: OO JS
http://ajaxian.com/archives/fresh-logic-studios-scripts-oo-js
Ajax MVC:
http://ajaxian.com/archives/ajax-mvc-so-to-speak
http://www.alexatnet.com/Blog/Index/2006-08-04/javascript-model-view-controller-with-dojo-toolkit
Adventures in JavaScript testing:
http://ajaxian.com/archives/adventures-in-javascript-testing-slides
Ajax & REST :
http://www-128.ibm.com/developerworks/java/library/wa-ajaxarch/
Eliminating async Javascript callbacks by preprocessing :
http://ajaxian.com/archives/eliminating-async-javascript-callbacks-by-preprocessing
IE + JavaScript Performance Recommendations :
http://blogs.msdn.com/ie/archive/2006/08/28/728654.aspx
Dramatically improved IE7 JavaScript performance :
http://ajaxian.com/archives/dramatically-improved-ie7-javascript-performance
http://ajaxian.com/archives/improved-javascript-performance-in-ie7
Scope in JavaScript :
http://www.digital-web.com/articles/scope_in_javascript/
Ajax services :
http://www.agmweb.ca/blog/index.php?p=50
Live Filter :
http://unspace.ca/discover/livefilter/
JavaScript control of throbber :
http://sandbox.sourcelabs.com/wikiality/throbber
Objectifying JavaScript :
http://www.digital-web.com/articles/objectifying_javascript/
Prototype Carousel Widget :
http://ajaxian.com/archives/prototype-carousel-widget
Tracking Ajax Requests in Analytics
http://www.ajax-blog.com/tracking-ajax-requests-in-analytics.html
jQuery Image Gallery: Transitions, thumbnails, reflections
http://ajaxian.com/archives/jquery-image-gallery-transitions-thumbnails-reflections
정규식
http://bluebreeze.co.kr/tag/정규식
Hacking Web 2.0 Applications with Firefox
http://www.securityfocus.com/infocus/1879
Usability for Rich Internet Applications(필히읽어보세요)
http://www.digital-web.com/articles/usability_for_rich_internet_applications/
AJAX Feedback Mechanism
http://www.ibegin.com/blog/p_ajax_feedback_mechanism.html
Making Javascript DOM a Piece of Cake with the graft() Function
http://schf.uc.org/articles/2006/10/15/making-javascript-dom-a-piece-of-cake-with-the-graft-function
Ajax Loding image
http://www.ajaxload.info/
Fixing the Back Button and Enabling Bookmarking for AJAX Apps
http://www.contentwithstyle.co.uk/Articles/38/fixing-the-back-button-and-enabling-bookmarking-for-ajax-apps
Tuning AJAX
http://www.xml.com/lpt/a/2005/11/30/tuning-ajax-performance.html
Ajax indicators
http://www.napyfab.com/ajax-indicators/

CSS Library
각종CSS : http://www.dynamicdrive.com/style/  
W3C 규격 번역문 :http://trio.co.kr/
Yahoo! Design Pattern Library : http://developer.yahoo.com/ypatterns/
Yahoo! UI Library (YUI) : http://developer.yahoo.com/yui/

CSS Articles
Architecting CSS:
http://www.digital-web.com/articles/architecting_css/
transcorners:
http://inviz.ru/moo/meet-transcorners
12 Lessons for Those Afraid of CSS and Standards:
http://ajaxian.com/archives/12-lessons-for-those-afraid-of-css-and-standards
A CSS Crossfader :
http://mikeomatic.net/?p=78
Push my button :
http://www.digital-web.com/articles/push_my_button/
Details on our CSS changes for IE7
http://blogs.msdn.com/ie/archive/2006/08/22/712830.aspx
폼 css
http://www.badboy.ro/articles/2005-07-23/index.php
테이블 css
http://icant.co.uk/csstablegallery/index.php?css=2

Posted by 전용우
,