태그 : prototype(6) | 전체태그
  • Prototype에 대하여...
  • 카테고리 : Javascript    2007/11/13 09:58
  • 당신은 Prototype에 대하여 얼마나 잘 알고 있나요?

    위 글을 보고 몇자 적어봅니다.
    알고 있는 부분은 빼고 나중에 참고하여 적을것들에 대해서만 적어둡니다.
    //바르지 못한 방법:
    Event.observe('myContainer', 'click', doSomeMagic);

    //적당한 방법: 논쟁의 여지가 있지만 객체지향적이다!
    $('myContainer').observe('click', doSomeMagic);

    흠.. 전자를 사용하였는데.. 논쟁의 여지가 있는줄에 대해서는 알지 못하였다.


    //바르지 못한 방법:
    $$('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
        }))
    )



    흠..
    invoke, new Template의 경우 지금까지 사용하지 않았었군요.
    상당히 편리한 메소드이군요..


    그외에 것들

    $(nextmonth).addClassName('calcontrol');
    $(nextmonth).addClassName('calnextmonth');
    $(nextmonth).observe('click',this.nextmonth);

    위의 firejune님이 소개한 곳에도 나오지만....
    아래와 같이 편하게 추가가능하군요.
    $(nextmonth).addClassName('calcontrol calnextmonth').observe('click', this.nextmonth);




    var left1 = $('left1');
    // creating array of strings and iterating over them
    $w('learn play grow join').each(function(s){
        left1.removeClassName(s);
    });

    나 같은 경우...
    'learn|play|grow|join'.split('|').each(function(s) {}); 로 사용했는데... $w를 사용하였군요.
    어느게 더 나은 결과를 보여줄지는 테스트를 해봐야겠군요..



    틀린경우
    $('someLink').observe('click', function(){doSomething(); returnfalse; })

    옳은 경우
    $('someLink').observe('click', function(e){e.stop(); doSomething(); })

    흠.. 글쿤요.. return false; 가 오난 e.stop();으로 이벤트를 종료시키는군요... 흠... 흠흠..

     
  • 트랙백 0 : 덧글 0
  • 롤링 배너 Protype 기반
  • 카테고리 : Javascript    2007/10/02 07:31
  • var BANNER = Class.create();
    BANNER.prototype = {
    initialize: function(banners, options){
    this.banners = banners;
    this.options = Object.extend({
    id: 'banner',
    width: 0,
    height: 0,
    interval: 5,
    no: 0,
    type: 'normal' // 배너 출력 형태 기본형 : normal, 수직 : vertical, horizon: 수평, fade: 점점 밝어짐
    }, options || {});


    document.write('
    ');
    document.write('
    ');
    document.write('
    ');

    this.node = $(this.options.id);
    this.options.cnt = banners.length;

    this.setBanner();
    this.roll = setInterval(this.rollingBanner.bind(this), (this.options.interval*1000));
    },

    setBanner: function()
    {
    var banner = {};
    var dsp = '';

    for(var i=0; i {
    banner = document.createElement('div');
    banner.style.backgroundImage = 'url('+this.banners[i].img+')';
    banner.style.cursor = 'pointer';
    banner.attr = this;
    banner.setAttribute('loc', this.banners[i].link);

    banner.onmouseover = function()
    {
    clearInterval(this.attr.roll);
    };

    banner.onmouseout = function()
    {
    this.attr.roll = setInterval(this.attr.rollingBanner.bind(this.attr), (this.attr.options.interval*1000));
    };

    banner.onclick = function()
    {
    window.location.href = this.getAttribute('loc');
    };

    if(this.options.type == 'horizon')
    Element.setStyle(banner, {width:this.options.width+'px', height:this.options.height+'px', cssFloat:'left'});
    else
    Element.setStyle(banner, {width:this.options.width+'px', height:this.options.height+'px'});

    this.node.appendChild(banner);
    }
    },

    rollingBanner: function()
    {
    //this.preBanNo = this.options.no;
    this.options.preNo = this.options.no;
    this.options.no++;

    this.options.curNo = this.options.no;
    BANNER.Effect.start(this.options);
    }
    }

    BANNER.Effect = {
    start: function(options)
    {
    this.options = Object.extend({
    start:0,
    finish:10,
    types:['vertical','horizon','fade']
    }, options || {});

    /* Todo: rand는 추후 추가
    if(this.options.type == 'rand')
    {
    var randNo = (Math.floor(Math.random()*this.options.types.length));
    this.options.type = this.options.types[randNo];
    }
    */
    this.node = $(this.options.id);

    if(this.options.type == 'normal') this[this.options.type]();
    else this.interval = setInterval(this[this.options.type].bind(this), 20);
    },

    normal: function()
    {
    this.changeNode();
    },

    vertical: function()
    {
    if(this.options.start == 20)
    {
    clearInterval(this.interval);
    this.changeNode();
    this.options.start = 0;
    }


    var per = (0.05*this.options.start);
    var top = (this.options.height*per);

    this.node.style.top = '-'+top+'px';
    this.options.start++;
    },

    horizon: function()
    {
    if(this.options.start == 40)
    {
    clearInterval(this.interval);
    this.changeNode();
    this.options.start = 0;
    }


    var per = (0.025*this.options.start);
    var left = (this.options.width*per);

    this.node.style.left = '-'+left+'px';
    this.options.start++;
    },

    /* 추후 추가 예정 */
    afade: function()
    {
    },

    changeNode: function()
    {
    var divs = this.node.getElementsByTagName('div');

    var tNode = [];
    for(var i=0; i {
    if(i==0)
    {
    tNode=divs[i];
    Element.remove(divs[i]);
    tNode.style.position = 'static';
    }
    }

    this.node.appendChild(tNode);
    }
    };


    위의 내용은 banner.js 파일의 내용이며,

    사용법은 다음과 같습니다.


    <script>
    var arBanner = [];
    arBanner[0] = {

       link:'http://16pounds.gamelamp.com/event/event_0709_v3.html',
       img:'http://image.gamelamp.com/16pounds/event/07_0920_friend/ad_01.jpg', target:'blank'};

    arBanner[1] = {
       link:'http://16pounds.gamelamp.com/event/event_0709_v1.html',
       img:'http://image.gamelamp.com/16pounds/event/07_0831_obt/ad_02.jpg', target:'self'};

    arBanner[2] = {
       link:'http://16pounds.gamelamp.com/event/event_0709_v3.html',
       img:'http://image.gamelamp.com/16pounds/event/07_0831_obt/ad_03_n.jpg', target:'blank'};


    new BANNER(arBanner, {width:664, height:245, interval:3,type:'vertical'});
    </script>

    배너를 배열에 담아주소 링크를 넣어주시면 됩니다.


    new Banner의 인자값 설명
    arBanner : 배너리스트
    width: 매너 폭
    height:높이

    interval : 인터발 타임
    type : 'vertical', 'normal', 'horizon' 


    샘플을 보시기 위해서 아래의 링크를 클릭하시면 됩니다.

    http://gudals.com/ulTest/banner.html



    참조 : 위의 링크에서 확인하실 수 있습니다.
    FLASH로 작성된 걸 보다가 메모리 CPU를 먹는걸 보고 만들어야겠다고 생각해서 만들긴 했는데
    적용하기에는 조금 부족합니다.

    소스에서 보시듯 Todo 리스트 역시 있거..
    귀차니즘에 빠진거죠~~~~~~~~~! 누군가 더 멋지게 만들어준다면 쌩큐~~~! ㅡ.ㅡ;;;;
  • 트랙백 0 : 덧글 0
  • 이미지 한장으로 애니매이션 만들기..
  • 카테고리 : Javascript    2007/08/01 14:27
  • 사용자 삽입 이미지
    자바스크립트를 이용해서 다음과 같은 이미지를 애니매이션 효과를 주는 스크립트입니다.
    물론 gif로 처리할수도 있지만 이와 같은 방법으로 처리 한다는것도 상당히 재미있는 부분일수 있습니다.

    script 소스


    var Ani = Class.create();
    Ani.prototype = {

    initialize: function(img, element, options){

    this.options = Object.extend({
    cnt: 0, // 애니메이션 몇장의 컷인가?
    width: 0, // 애니메이션 크기
    height: 0, // 애니메이션 높이
    line: 0, // 이미지 줄
    field: 0, // 이미지 몇개에
    x: 0, // 시작 x점
    y: 0, // 시작 y점
    interval: 0, // 인터발 시간이며, 이 시간은 javascript 의 시간이다. 1초 = 1000
    repeat: 0, // 이미지 반복횟수
    type: 'image' // 타입은 background, image 형 두개가 있다.
    }, options || {});

    this.img = img;
    this.element = (typeof(element) == 'string') ? $(element) : element;


    this.aniNode = document.createElement('div');
    Element.setStyle(this.aniNode, {width:this.options.width+'px', height:this.options.height+'px', overflow:'hidden', position:'relative'});
    this.element.appendChild(this.aniNode);

    this.options.x = this.options.x*-1;
    this.options.y = this.options.y*-1;
    this[this.options.type]();
    this.repeat = 1;
    this.cnt = 0;

    this.line = 0;
    this.field = 0;
    this.interVal = setInterval(this.ani.bind(this), this.options.interval);
    },

    ani: function()
    {
    var x = y = 0;

    if((this.options.cnt-2) < this.cnt)
    {
    this.cnt = 0;
    this.repeat++;

    this.line = 0;
    this.field = 0;
    }

    // 리피트가 넘으면 종료
    if(this.options.repeat < this.repeat)
    {
    clearInterval(this.interVal);
    return;
    }


    //alert(this.cnt%this.options.field);
    if((this.cnt%this.options.field) == (this.options.field-1))
    {

    this.line++;
    this.field = 0;
    }

    y = (this.line * this.options.height)*-1;
    x = (this.field * this.options.width)*-1;
    y = this.options.y+y;
    x = this.options.x+x;


    if(this.options.type == 'background')
    {
    this.aniNode.style.backgroundPosition = x+'px '+y+'px';
    }
    else
    {
    this.imgNode.style.top = y+'px';
    this.imgNode.style.left = x+'px';
    }

    this.cnt++;
    this.field++;

    },

    background: function()
    {
    this.aniNode.style.backgroundImage = 'url('+this.img+')';
    this.aniNode.style.backgroundPosition = this.options.x+'px '+this.options.y+'px';
    },

    image: function()
    {
    this.imgNode = document.createElement('img');
    this.imgNode.setAttribute('src', this.img);
    Element.setStyle(this.imgNode, {position:'absolute', top:this.options.y, left:this.options.x});
    this.aniNode.appendChild(this.imgNode);
    }
    }



    http://www.gudals.com/gostop/animation.html

    샘플은 위의 링크에서 확인하실 수 있습니다.



    보다 자세한 내용은 소스를 참조하시기 바랍니다.
  • 트랙백 0 : 덧글 0
1 / 2